tizen 2.3 release tizen_2.3 submit/tizen_2.3/20150202.082027 tizen_2.3_release
authorjk7744.park <jk7744.park@samsung.com>
Sun, 1 Feb 2015 05:37:30 +0000 (14:37 +0900)
committerjk7744.park <jk7744.park@samsung.com>
Sun, 1 Feb 2015 05:37:30 +0000 (14:37 +0900)
430 files changed:
AUTHORS [new file with mode: 0644]
CMakeLists.txt [new file with mode: 0644]
LICENSE [new file with mode: 0644]
ace/CMakeLists.txt [new file with mode: 0644]
ace/DESCRIPTION [new file with mode: 0644]
ace/configuration/UnrestrictedPolicy.xml [new file with mode: 0644]
ace/configuration/WAC2.0Policy.xml [new file with mode: 0644]
ace/configuration/bondixml.xsd [new file with mode: 0644]
ace/dao/AceDAO.cpp [new file with mode: 0644]
ace/dao/AceDAOConversions.cpp [new file with mode: 0644]
ace/dao/AceDAOReadOnly.cpp [new file with mode: 0644]
ace/dao/AceDAOUtilities.cpp [new file with mode: 0644]
ace/dao/AceDatabase.cpp [new file with mode: 0644]
ace/dao/BaseAttribute.cpp [new file with mode: 0644]
ace/dao/CMakeLists.txt [new file with mode: 0644]
ace/dao/PromptModel.cpp [new file with mode: 0644]
ace/engine/Attribute.cpp [new file with mode: 0644]
ace/engine/CombinerImpl.cpp [new file with mode: 0644]
ace/engine/Condition.cpp [new file with mode: 0644]
ace/engine/ConfigurationManager.cpp [new file with mode: 0644]
ace/engine/Policy.cpp [new file with mode: 0644]
ace/engine/PolicyEnforcementPoint.cpp [new file with mode: 0644]
ace/engine/PolicyEvaluator.cpp [new file with mode: 0644]
ace/engine/PolicyInformationPoint.cpp [new file with mode: 0644]
ace/engine/Rule.cpp [new file with mode: 0644]
ace/engine/SettingsLogic.cpp [new file with mode: 0644]
ace/engine/Subject.cpp [new file with mode: 0644]
ace/engine/TreeNode.cpp [new file with mode: 0644]
ace/engine/parser.cpp [new file with mode: 0644]
ace/include/ace-dao-ro/AceDAOConversions.h [new file with mode: 0644]
ace/include/ace-dao-ro/AceDAOReadOnly.h [new file with mode: 0644]
ace/include/ace-dao-ro/AceDAOUtilities.h [new file with mode: 0644]
ace/include/ace-dao-ro/AceDatabase.h [new file with mode: 0644]
ace/include/ace-dao-ro/AppTypes.h [new file with mode: 0644]
ace/include/ace-dao-ro/BaseAttribute.h [new file with mode: 0644]
ace/include/ace-dao-ro/BasePermission.h [new file with mode: 0644]
ace/include/ace-dao-ro/IRequest.h [new file with mode: 0644]
ace/include/ace-dao-ro/PreferenceTypes.h [new file with mode: 0644]
ace/include/ace-dao-ro/PromptModel.h [new file with mode: 0644]
ace/include/ace-dao-ro/TimedVerdict.h [new file with mode: 0644]
ace/include/ace-dao-ro/ValidityTypes.h [new file with mode: 0644]
ace/include/ace-dao-ro/VerdictTypes.h [new file with mode: 0644]
ace/include/ace-dao-ro/common_dao_types.h [new file with mode: 0644]
ace/include/ace-dao-rw/AceDAO.h [new file with mode: 0644]
ace/include/ace/AbstractPolicyEnforcementPoint.h [new file with mode: 0644]
ace/include/ace/AbstractPolicyInformationPoint.h [new file with mode: 0644]
ace/include/ace/AbstractTreeElement.h [new file with mode: 0644]
ace/include/ace/AsyncVerdictResultListener.h [new file with mode: 0644]
ace/include/ace/Attribute.h [new file with mode: 0644]
ace/include/ace/Combiner.h [new file with mode: 0644]
ace/include/ace/CombinerImpl.h [new file with mode: 0644]
ace/include/ace/Condition.h [new file with mode: 0644]
ace/include/ace/ConfigurationManager.h [new file with mode: 0644]
ace/include/ace/Constants.h [new file with mode: 0644]
ace/include/ace/Effect.h [new file with mode: 0644]
ace/include/ace/PermissionTriple.h [new file with mode: 0644]
ace/include/ace/Policy.h [new file with mode: 0644]
ace/include/ace/PolicyEffect.h [new file with mode: 0644]
ace/include/ace/PolicyEnforcementPoint.h [new file with mode: 0644]
ace/include/ace/PolicyEvaluator.h [new file with mode: 0644]
ace/include/ace/PolicyEvaluatorFactory.h [new file with mode: 0644]
ace/include/ace/PolicyInformationPoint.h [new file with mode: 0644]
ace/include/ace/PolicyResult.h [new file with mode: 0644]
ace/include/ace/PolicySet.h [new file with mode: 0644]
ace/include/ace/Preference.h [new file with mode: 0644]
ace/include/ace/PromptDecision.h [new file with mode: 0644]
ace/include/ace/Request.h [new file with mode: 0644]
ace/include/ace/Rule.h [new file with mode: 0644]
ace/include/ace/SettingsLogic.h [new file with mode: 0644]
ace/include/ace/Subject.h [new file with mode: 0644]
ace/include/ace/TestTimer.h [new file with mode: 0644]
ace/include/ace/TreeNode.h [new file with mode: 0644]
ace/include/ace/UserDecision.h [new file with mode: 0644]
ace/include/ace/Verdict.h [new file with mode: 0644]
ace/include/ace/WRT_INTERFACE.h [new file with mode: 0644]
ace/include/ace/WidgetUsageModel.h [new file with mode: 0644]
ace/include/ace/acf_consts.h [new file with mode: 0644]
ace/include/ace/parser.h [new file with mode: 0644]
ace/orm/ace_db [new file with mode: 0644]
ace/orm/ace_db_definitions [new file with mode: 0644]
ace/orm/ace_db_sql_generator.h [new file with mode: 0644]
ace/orm/gen_db_md5.sh [new file with mode: 0755]
ace/orm/orm_generator_ace.h [new file with mode: 0644]
ace/orm/version_db [new file with mode: 0644]
ace_client/CMakeLists.txt [new file with mode: 0644]
ace_client/include/ace-client/ace_client.h [new file with mode: 0644]
ace_client/include/ace-client/ace_client_helper.h [new file with mode: 0644]
ace_client/include/ace-client/ace_client_types.h [new file with mode: 0644]
ace_client/include/ace_api_client.h [new file with mode: 0644]
ace_client/include/ace_popup_handler.h [new file with mode: 0644]
ace_client/src/CMakeLists.txt [new file with mode: 0644]
ace_client/src/ace_api_client.cpp [new file with mode: 0644]
ace_client/src/ace_client.cpp [new file with mode: 0644]
ace_client/src/example/CMakeLists.txt [new file with mode: 0644]
ace_client/src/example/ace-thin-client-example.cpp [new file with mode: 0644]
ace_common/CMakeLists.txt [new file with mode: 0644]
ace_common/include/ace_api_common.h [new file with mode: 0644]
ace_install/CMakeLists.txt [new file with mode: 0644]
ace_install/include/ace_api_install.h [new file with mode: 0644]
ace_install/src/CMakeLists.txt [new file with mode: 0644]
ace_install/src/ace_api_install.cpp [new file with mode: 0644]
ace_popup_validation/CMakeLists.txt [new file with mode: 0644]
ace_popup_validation/include/ace_api_popup_validation.h [new file with mode: 0644]
ace_popup_validation/src/CMakeLists.txt [new file with mode: 0644]
ace_popup_validation/src/ace_api_popup_validation.cpp [new file with mode: 0644]
ace_settings/CMakeLists.txt [new file with mode: 0644]
ace_settings/include/ace_api_settings.h [new file with mode: 0644]
ace_settings/src/CMakeLists.txt [new file with mode: 0644]
ace_settings/src/ace_api_settings.cpp [new file with mode: 0644]
build/CMakeLists.txt [new file with mode: 0644]
build/ace/CMakeLists.txt [new file with mode: 0644]
build/ace/security-dao-ro.pc.in [new file with mode: 0644]
build/ace/security-dao-rw.pc.in [new file with mode: 0644]
build/ace/security.pc.in [new file with mode: 0644]
build/ace_client/CMakeLists.txt [new file with mode: 0644]
build/ace_client/security-client.pc.in [new file with mode: 0644]
build/ace_install/CMakeLists.txt [new file with mode: 0644]
build/ace_install/security-install.pc.in [new file with mode: 0644]
build/ace_popup_validation/CMakeLists.txt [new file with mode: 0644]
build/ace_popup_validation/security-popup-validation.pc.in [new file with mode: 0644]
build/ace_settings/CMakeLists.txt [new file with mode: 0644]
build/ace_settings/security-settings.pc.in [new file with mode: 0644]
build/communication_client/CMakeLists.txt [new file with mode: 0644]
build/communication_client/security-communication-client.pc.in [new file with mode: 0644]
build/wrt-security/CMakeLists.txt [new file with mode: 0644]
build/wrt-security/security-core.pc.in [new file with mode: 0644]
build/wrt_ocsp/CMakeLists.txt [new file with mode: 0644]
build/wrt_ocsp/security-wrt-ocsp.pc.in [new file with mode: 0644]
commons/CMakeLists.txt [new file with mode: 0644]
commons/LICENSE [new file with mode: 0644]
commons/NOTICE [new file with mode: 0644]
commons/build/CMakeLists.txt [new file with mode: 0644]
commons/build/core/CMakeLists.txt [new file with mode: 0644]
commons/build/core/DESCRIPTION [new file with mode: 0644]
commons/build/core/wrt-security-commons.pc.in [new file with mode: 0644]
commons/build/db/CMakeLists.txt [new file with mode: 0644]
commons/build/db/wrt-security-commons-db.pc.in [new file with mode: 0644]
commons/build/log/CMakeLists.txt [new file with mode: 0644]
commons/build/log/wrt-security-commons-log.pc.in [new file with mode: 0644]
commons/modules/CMakeLists.txt [new file with mode: 0644]
commons/modules/core/DESCRIPTION [new file with mode: 0644]
commons/modules/core/config.cmake [new file with mode: 0644]
commons/modules/core/include/DESCRIPTION [new file with mode: 0644]
commons/modules/core/include/dpl/assert.h [new file with mode: 0644]
commons/modules/core/include/dpl/availability.h [new file with mode: 0644]
commons/modules/core/include/dpl/char_traits.h [new file with mode: 0644]
commons/modules/core/include/dpl/colors.h [new file with mode: 0644]
commons/modules/core/include/dpl/errno_string.h [new file with mode: 0644]
commons/modules/core/include/dpl/exception.h [new file with mode: 0644]
commons/modules/core/include/dpl/foreach.h [new file with mode: 0644]
commons/modules/core/include/dpl/free_deleter.h [new file with mode: 0644]
commons/modules/core/include/dpl/generic_event.h [new file with mode: 0644]
commons/modules/core/include/dpl/mutex.h [new file with mode: 0644]
commons/modules/core/include/dpl/noncopyable.h [new file with mode: 0644]
commons/modules/core/include/dpl/optional_typedefs.h [new file with mode: 0644]
commons/modules/core/include/dpl/preprocessor.h [new file with mode: 0644]
commons/modules/core/include/dpl/recursive_mutex.h [new file with mode: 0644]
commons/modules/core/include/dpl/scoped_free.h [new file with mode: 0644]
commons/modules/core/include/dpl/scoped_resource.h [new file with mode: 0644]
commons/modules/core/include/dpl/serialization.h [new file with mode: 0644]
commons/modules/core/include/dpl/single_instance.h [new file with mode: 0644]
commons/modules/core/include/dpl/singleton.h [new file with mode: 0644]
commons/modules/core/include/dpl/singleton_impl.h [new file with mode: 0644]
commons/modules/core/include/dpl/singleton_safe_impl.h [new file with mode: 0644]
commons/modules/core/include/dpl/string.h [new file with mode: 0644]
commons/modules/core/include/dpl/thread.h [new file with mode: 0644]
commons/modules/core/include/dpl/type_list.h [new file with mode: 0644]
commons/modules/core/include/dpl/waitable_event.h [new file with mode: 0644]
commons/modules/core/include/dpl/waitable_handle.h [new file with mode: 0644]
commons/modules/core/include/dpl/waitable_handle_watch_support.h [new file with mode: 0644]
commons/modules/core/include/dpl/workaround.h [new file with mode: 0644]
commons/modules/core/src/DESCRIPTION [new file with mode: 0644]
commons/modules/core/src/assert.cpp [new file with mode: 0644]
commons/modules/core/src/colors.cpp [new file with mode: 0644]
commons/modules/core/src/errno_string.cpp [new file with mode: 0644]
commons/modules/core/src/exception.cpp [new file with mode: 0644]
commons/modules/core/src/mutex.cpp [new file with mode: 0644]
commons/modules/core/src/noncopyable.cpp [new file with mode: 0644]
commons/modules/core/src/recursive_mutex.cpp [new file with mode: 0644]
commons/modules/core/src/serialization.cpp [new file with mode: 0644]
commons/modules/core/src/single_instance.cpp [new file with mode: 0644]
commons/modules/core/src/singleton.cpp [new file with mode: 0644]
commons/modules/core/src/string.cpp [new file with mode: 0644]
commons/modules/core/src/thread.cpp [new file with mode: 0644]
commons/modules/core/src/waitable_event.cpp [new file with mode: 0644]
commons/modules/core/src/waitable_handle.cpp [new file with mode: 0644]
commons/modules/core/src/waitable_handle_watch_support.cpp [new file with mode: 0644]
commons/modules/db/config.cmake [new file with mode: 0644]
commons/modules/db/include/dpl/db/naive_synchronization_object.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/orm.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/orm_generator.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/orm_interface.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/orm_macros.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/sql_connection.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/thread_database_support.h [new file with mode: 0644]
commons/modules/db/src/naive_synchronization_object.cpp [new file with mode: 0644]
commons/modules/db/src/orm.cpp [new file with mode: 0644]
commons/modules/db/src/sql_connection.cpp [new file with mode: 0644]
commons/modules/db/src/thread_database_support.cpp [new file with mode: 0644]
commons/modules/log/config.cmake [new file with mode: 0644]
commons/modules/log/include/dpl/log/abstract_log_provider.h [new file with mode: 0644]
commons/modules/log/include/dpl/log/dlog_log_provider.h [new file with mode: 0644]
commons/modules/log/include/dpl/log/log.h [new file with mode: 0644]
commons/modules/log/include/dpl/log/old_style_log_provider.h [new file with mode: 0644]
commons/modules/log/include/dpl/log/secure_log.h [new file with mode: 0644]
commons/modules/log/src/abstract_log_provider.cpp [new file with mode: 0644]
commons/modules/log/src/dlog_log_provider.cpp [new file with mode: 0644]
commons/modules/log/src/log.cpp [new file with mode: 0644]
commons/modules/log/src/old_style_log_provider.cpp [new file with mode: 0644]
commons/wrt-commons [new file with mode: 0644]
communication_client/include/SecurityCommunicationClient.h [new file with mode: 0644]
communication_client/src/SecurityCommunicationClient.cpp [new file with mode: 0644]
etc/CMakeLists.txt [new file with mode: 0644]
etc/schema.xsd [new file with mode: 0644]
etc/wrt_security_change_policy.sh [new file with mode: 0644]
etc/wrt_security_create_clean_db.sh [new file with mode: 0644]
mockups/AceDAOReadOnly_mock.cpp [new file with mode: 0644]
mockups/AceDAOReadOnly_mock.h [new file with mode: 0644]
mockups/PolicyInformationPoint_mock.h [new file with mode: 0644]
mockups/communication_client_mock.cpp [new file with mode: 0644]
mockups/communication_client_mock.h [new file with mode: 0644]
packaging/wrt-security.changes [new file with mode: 0644]
packaging/wrt-security.manifest [new file with mode: 0644]
packaging/wrt-security.spec [new file with mode: 0644]
socket_connection/client/SecuritySocketClient.cpp [new file with mode: 0644]
socket_connection/client/SecuritySocketClient.h [new file with mode: 0644]
socket_connection/connection/SocketConnection.cpp [new file with mode: 0644]
socket_connection/connection/SocketConnection.h [new file with mode: 0644]
socket_connection/connection/SocketStream.cpp [new file with mode: 0644]
socket_connection/connection/SocketStream.h [new file with mode: 0644]
src/CMakeLists.txt [new file with mode: 0644]
src/TODO.txt [new file with mode: 0644]
src/daemon/dbus/org.tizen.SecurityDaemon.service [new file with mode: 0644]
src/daemon/dbus/security_daemon_dbus_config.h [new file with mode: 0644]
src/daemon/dbus/security_dbus_service.cpp [new file with mode: 0644]
src/daemon/dbus/security_dbus_service.h [new file with mode: 0644]
src/daemon/security_daemon.cpp [new file with mode: 0644]
src/daemon/security_daemon.h [new file with mode: 0644]
src/daemon/sockets/api/callback_api.h [new file with mode: 0644]
src/daemon/sockets/security_daemon_socket_config.h [new file with mode: 0644]
src/daemon/sockets/security_socket_service.cpp [new file with mode: 0644]
src/daemon/sockets/security_socket_service.h [new file with mode: 0644]
src/main.cpp [new file with mode: 0644]
src/services/ace/ace_server_api.h [new file with mode: 0644]
src/services/ace/ace_service.cpp [new file with mode: 0644]
src/services/ace/dbus/ace_server_dbus_interface.cpp [new file with mode: 0644]
src/services/ace/dbus/ace_server_dbus_interface.h [new file with mode: 0644]
src/services/ace/dbus/api/ace_server_dbus_api.h [new file with mode: 0644]
src/services/ace/logic/acf_consts.h [new file with mode: 0644]
src/services/ace/logic/attribute_facade.cpp [new file with mode: 0644]
src/services/ace/logic/attribute_facade.h [new file with mode: 0644]
src/services/ace/logic/security_controller.cpp [new file with mode: 0644]
src/services/ace/logic/security_controller.h [new file with mode: 0644]
src/services/ace/logic/security_logic.cpp [new file with mode: 0644]
src/services/ace/logic/security_logic.h [new file with mode: 0644]
src/services/ace/logic/simple_roaming_agent.cpp [new file with mode: 0644]
src/services/ace/logic/simple_roaming_agent.h [new file with mode: 0755]
src/services/ace/socket/ace_service_callbacks.cpp [new file with mode: 0644]
src/services/ace/socket/ace_service_callbacks.h [new file with mode: 0644]
src/services/ace/socket/api/ace_service_callbacks_api.h [new file with mode: 0644]
src/services/caller/security_caller.cpp [new file with mode: 0644]
src/services/caller/security_caller.h [new file with mode: 0644]
src/services/ocsp/dbus/api/ocsp_server_dbus_api.h [new file with mode: 0644]
src/services/ocsp/dbus/ocsp_server_dbus_interface.cpp [new file with mode: 0644]
src/services/ocsp/dbus/ocsp_server_dbus_interface.h [new file with mode: 0644]
src/services/ocsp/ocsp_server_api.h [new file with mode: 0644]
src/services/ocsp/ocsp_service.cpp [new file with mode: 0644]
src/services/ocsp/socket/api/ocsp_service_callbacks_api.h [new file with mode: 0644]
src/services/ocsp/socket/ocsp_service_callbacks.cpp [new file with mode: 0644]
src/services/ocsp/socket/ocsp_service_callbacks.h [new file with mode: 0644]
src/services/popup/dbus/popup_response_dbus_interface.cpp [new file with mode: 0644]
src/services/popup/dbus/popup_response_dbus_interface.h [new file with mode: 0644]
src/services/popup/popup_ace_data_types.h [new file with mode: 0644]
src/services/popup/popup_response_server_api.h [new file with mode: 0644]
src/services/popup/socket/api/popup_service_callbacks_api.h [new file with mode: 0644]
src/services/popup/socket/popup_service_callbacks.cpp [new file with mode: 0644]
src/services/popup/socket/popup_service_callbacks.h [new file with mode: 0644]
systemd/wrt-security-daemon.service [new file with mode: 0644]
systemd/wrt-security-daemon.socket [new file with mode: 0644]
tests/CMakeLists.txt [new file with mode: 0644]
tests/ace/AttributeSetter.cpp [new file with mode: 0644]
tests/ace/AttributeSetter.h [new file with mode: 0644]
tests/ace/CMakeLists.txt [new file with mode: 0644]
tests/ace/Interfaces.cpp [new file with mode: 0644]
tests/ace/Interfaces.h [new file with mode: 0644]
tests/ace/PEPSingleton.cpp [new file with mode: 0644]
tests/ace/PEPSingleton.h [new file with mode: 0644]
tests/ace/TestSuite01.cpp [new file with mode: 0644]
tests/ace/TestSuite02.cpp [new file with mode: 0644]
tests/ace/TestSuite03.cpp [new file with mode: 0644]
tests/ace/TestSuite04.cpp [new file with mode: 0644]
tests/ace/TestSuite05.cpp [new file with mode: 0644]
tests/ace/TestSuite06.cpp [new file with mode: 0644]
tests/ace/ace_tests.cpp [new file with mode: 0644]
tests/ace/loop_control.cpp [new file with mode: 0644]
tests/ace/loop_control.h [new file with mode: 0644]
tests/ace/test-configuration/CMTest/CMakeLists.txt [new file with mode: 0644]
tests/ace/test-configuration/CMTest/active/CMakeLists.txt [new file with mode: 0644]
tests/ace/test-configuration/CMTest/active/bondixml.dtd [new file with mode: 0644]
tests/ace/test-configuration/CMTest/active/pms_general-test.xml [new file with mode: 0644]
tests/ace/test-configuration/CMTest/pms_config.xml [new file with mode: 0644]
tests/ace/test-configuration/CMTest/pms_general-test.xml [new file with mode: 0644]
tests/ace/test-configuration/CMTest/policyTest1.xml [new file with mode: 0644]
tests/ace/test-configuration/CMTest/policyTest2.xml [new file with mode: 0644]
tests/ace/test-configuration/CMTest/policyTest3.xml [new file with mode: 0644]
tests/ace/test-configuration/CMakeLists.txt [new file with mode: 0644]
tests/ace/test-configuration/TizenPolicy-test.xml [new file with mode: 0644]
tests/ace/test-configuration/WAC2.0Policy-test.xml [new file with mode: 0644]
tests/ace/test-configuration/attr_policy-example.xml [new file with mode: 0644]
tests/ace/test-configuration/attr_policy-example1.xml [new file with mode: 0644]
tests/ace/test-configuration/attr_policy-example2.xml [new file with mode: 0644]
tests/ace/test-configuration/attr_policy-example3.xml [new file with mode: 0644]
tests/ace/test-configuration/attr_policy-example4.xml [new file with mode: 0644]
tests/ace/test-configuration/attr_policy-example5.xml [new file with mode: 0644]
tests/ace/test-configuration/attr_policy-example6.xml [new file with mode: 0644]
tests/ace/test-configuration/attr_policy-example7.xml [new file with mode: 0644]
tests/ace/test-configuration/attr_policy-example8.xml [new file with mode: 0644]
tests/ace/test-configuration/attre_config.xml [new file with mode: 0644]
tests/ace/test-configuration/general-test.xml [new file with mode: 0644]
tests/ace/test-configuration/interceptpolicy.xml [new file with mode: 0644]
tests/ace/test-configuration/old_policy-example.xml [new file with mode: 0644]
tests/ace/test-configuration/policy-example.xml [new file with mode: 0644]
tests/ace/test-configuration/policy-example2.xml [new file with mode: 0644]
tests/ace/test-configuration/policy-example3.xml [new file with mode: 0644]
tests/ace/test-configuration/policy-test-gsettings.xml [new file with mode: 0644]
tests/ace/test-configuration/policy-test.xml [new file with mode: 0644]
tests/ace/test-configuration/policy-wac-2.0.xml [new file with mode: 0644]
tests/ace/test-configuration/policy_example.xml [new file with mode: 0644]
tests/ace/test-configuration/reproduce-abort-test.xml [new file with mode: 0644]
tests/ace/test-configuration/undefined-test.xml [new file with mode: 0644]
tests/ace/widget_installer.h [new file with mode: 0644]
tests/ace_client/CMakeLists.txt [new file with mode: 0644]
tests/ace_client/ace_client_tests.cpp [new file with mode: 0644]
tests/ace_client/test_cases.cpp [new file with mode: 0644]
tests/ace_install/CMakeLists.txt [new file with mode: 0644]
tests/ace_install/ace-install-api-demo-policy.xml [new file with mode: 0644]
tests/ace_install/ace_install_tests.cpp [new file with mode: 0644]
tests/ace_install/test_cases.cpp [new file with mode: 0644]
tests/ace_install/widget_installer.h [new file with mode: 0644]
tests/ace_settings/CMakeLists.txt [new file with mode: 0644]
tests/ace_settings/ace_settings_tests.cpp [new file with mode: 0644]
tests/ace_settings/test_cases.cpp [new file with mode: 0644]
tests/geolocation_security/CMakeLists.txt [new file with mode: 0644]
tests/geolocation_security/GeolocationPolicyTest1 [new file with mode: 0644]
tests/geolocation_security/GeolocationPolicyTest2 [new file with mode: 0644]
tests/geolocation_security/createGeolocationSecurityTest.sh [new file with mode: 0755]
tests/geolocation_security/geolocationSecurityTest/config1.xml [new file with mode: 0644]
tests/geolocation_security/geolocationSecurityTest/config2.xml [new file with mode: 0644]
tests/geolocation_security/geolocationSecurityTest/css/style.css [new file with mode: 0755]
tests/geolocation_security/geolocationSecurityTest/icon.png [new file with mode: 0755]
tests/geolocation_security/geolocationSecurityTest/index.html [new file with mode: 0755]
tests/geolocation_security/geolocationSecurityTest/js/TestEngine.js [new file with mode: 0644]
tests/geolocation_security/geolocationSecurityTest/js/WAC2.0/TestGeolocation.js [new file with mode: 0644]
tests/geolocation_security/geolocationSecurityTest/js/WAC2.0/TestGeolocationCallback1.js [new file with mode: 0644]
tests/geolocation_security/geolocationSecurityTest/js/WAC2.0/TestGeolocationCallback2.js [new file with mode: 0644]
tests/geolocation_security/geolocationSecurityTest/js/include.js [new file with mode: 0644]
tests/geolocation_security/geolocationSecurityTest/js/jquery.js [new file with mode: 0644]
tests/geolocation_security/wrt-tests-security-geolocation.sh [new file with mode: 0755]
tests/security-tests.sh [new file with mode: 0755]
tests/security_daemon_tests/CMakeLists.txt [new file with mode: 0644]
tests/security_daemon_tests/HOWTO.txt [new file with mode: 0644]
tests/security_daemon_tests/ace_ipc_test_cases.cpp [new file with mode: 0644]
tests/security_daemon_tests/fake_service.cpp [new file with mode: 0644]
tests/security_daemon_tests/fake_service.h [new file with mode: 0644]
tests/security_daemon_tests/ipc-tests-demo.xml [new file with mode: 0644]
tests/security_daemon_tests/main.cpp [new file with mode: 0644]
tests/security_daemon_tests/service_test_cases.cpp [new file with mode: 0644]
tests/smack_security/CMakeLists.txt [new file with mode: 0644]
tests/smack_security/PermitAllPolicy.xml [new file with mode: 0644]
tests/smack_security/createSmackSecurityTest.sh [new file with mode: 0755]
tests/smack_security/smackSecurityTest1/config.xml [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/css/style.css [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/index.html [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/TestEngine.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/CloseCallback.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/TestAccelerometer.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/TestCalendar.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/TestCamera.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/TestContact.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/TestDeviceInteraction.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/TestDevicestatus.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/TestFilesystem.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/TestGeolocation.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/TestMessaging.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/TestOrientation.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/WAC2.0/TestTask.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/include.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest1/js/jquery.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/config1.xml [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/config10.xml [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/config2.xml [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/config3.xml [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/config4.xml [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/config5.xml [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/config6.xml [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/config7.xml [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/config8.xml [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/config9.xml [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/css/style.css [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/index.html [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/TestEngine.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/CloseCallback.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/TestAccelerometer.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/TestCalendar.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/TestCamera.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/TestContact.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/TestDeviceInteraction.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/TestDevicestatus.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/TestFilesystem.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/TestGeolocation.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/TestMessaging.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/TestOrientation.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/WAC2.0/TestTask.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/include1.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/include10.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/include2.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/include3.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/include4.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/include5.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/include6.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/include7.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/include8.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/include9.js [new file with mode: 0644]
tests/smack_security/smackSecurityTest2/js/jquery.js [new file with mode: 0644]
tests/smack_security/wrt-tests-security-smack.sh [new file with mode: 0755]
tests/wrt-tests-security-all.sh [new file with mode: 0755]
wrt_ocsp/CMakeLists.txt [new file with mode: 0644]
wrt_ocsp/include/wrt_ocsp_api.h [new file with mode: 0644]
wrt_ocsp/src/CMakeLists.txt [new file with mode: 0644]
wrt_ocsp/src/wrt_ocsp_api.cpp [new file with mode: 0644]

diff --git a/AUTHORS b/AUTHORS
new file mode 100644 (file)
index 0000000..a62936f
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +1 @@
+Bumjin Im <bj.i@samsung.com>
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644 (file)
index 0000000..8e6b396
--- /dev/null
@@ -0,0 +1,155 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author
+# @brief
+#
+
+############################# Check minimum CMake version #####################
+
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT("wrt-security")
+
+############################# cmake packages ##################################
+
+INCLUDE(FindPkgConfig)
+
+############################# compilation defines #############################
+
+# EMPTY
+
+############################# compiler flags ##################################
+
+SET(CMAKE_C_FLAGS_PROFILING    "-O0 -g -pg")
+SET(CMAKE_CXX_FLAGS_PROFILING  "-O0 -std=c++0x -g -pg")
+SET(CMAKE_C_FLAGS_DEBUG        "-O0 -g")
+SET(CMAKE_CXX_FLAGS_DEBUG      "-O0 -std=c++0x -g")
+SET(CMAKE_C_FLAGS_RELEASE      "-O2 -g")
+SET(CMAKE_CXX_FLAGS_RELEASE    "-O2 -std=c++0x -g")
+SET(CMAKE_C_FLAGS_CCOV         "-O2 -g --coverage")
+SET(CMAKE_CXX_FLAGS_CCOV       "-O2 -std=c++0x -g --coverage")
+
+#SET(SMACK_ENABLE ON)
+
+OPTION(DPL_LOG "DPL logs status" ON)
+IF(DPL_LOG)
+    MESSAGE(STATUS "Logging enabled for DPL")
+    ADD_DEFINITIONS("-DDPL_LOGS_ENABLED")
+ELSE(DPL_LOG)
+    MESSAGE(STATUS "Logging disabled for DPL")
+ENDIF(DPL_LOG)
+
+# If supported for the target machine, emit position-independent code,suitable
+# for dynamic linking and avoiding any limit on the size of the global offset
+# table. This option makes a difference on the m68k, PowerPC and SPARC.
+# (BJ: our ARM too?)
+ADD_DEFINITIONS("-fPIC")
+
+# Set the default ELF image symbol visibility to hidden - all symbols will be
+# marked with this unless overridden within the code.
+#ADD_DEFINITIONS("-fvisibility=hidden")
+
+# Set compiler warning flags
+#ADD_DEFINITIONS("-Werror")                      # Make all warnings into errors.
+ADD_DEFINITIONS("-Wall")                        # Generate all warnings
+ADD_DEFINITIONS("-Wextra")                      # Generate even more extra warnings
+ADD_DEFINITIONS("-Wno-variadic-macros")         # Inhibit variadic macros warnings (needed for ORM)
+ADD_DEFINITIONS("-Wno-deprecated")               # No warnings about deprecated features
+ADD_DEFINITIONS("-std=c++0x")               # No warnings about deprecated features
+
+# DBUS_CONNECTION and ENABLE_PRIVACY_MANAGER should be enabled together to make
+# dbus and privacy manager code enabled 
+ADD_DEFINITIONS("-DSOCKET_CONNECTION")        #defines sockets as used IPC
+#ADD_DEFINITIONS("-DDBUS_CONNECTION")         #defines DBus as used IPC
+IF(ENABLE_PRIVACY_MANAGER EQUAL 1)
+ADD_DEFINITIONS("-DENABLE_PRIVACY_MANAGER")  #disables privacy manager from wrt-secuirty-daemon
+ENDIF()
+
+
+STRING(REGEX MATCH "([^.]*)" API_VERSION "${VERSION}")
+ADD_DEFINITIONS("-DAPI_VERSION=\"$(API_VERSION)\"")
+
+IF(SMACK_ENABLE)
+    ADD_DEFINITIONS("-DWRT_SMACK_ENABLED")
+ENDIF(SMACK_ENABLE)
+
+############################# Targets names ###################################
+
+SET(TARGET_DAEMON "wrt-security-daemon")
+SET(TARGET_ACE_DAO_RO_LIB "ace-dao-ro")
+SET(TARGET_ACE_DAO_RW_LIB "ace-dao-rw")
+SET(TARGET_ACE_LIB "ace")
+SET(TARGET_ACE_CLIENT_LIB "ace-client")
+SET(TARGET_ACE_SETTINGS_LIB "ace-settings")
+SET(TARGET_ACE_INSTALL_LIB "ace-install")
+SET(TARGET_ACE_POPUP_VALIDATION_LIB "ace-popup-validation")
+SET(TARGET_COMMUNICATION_CLIENT_LIB "communication-client")
+SET(TARGET_WRT_OCSP_LIB "wrt-ocsp")
+SET(TARGET_SEC_SRV_LIB "sec-srv")
+
+############################# Communicatin Client #############################
+
+SET(COMMUNICATION_CLIENT_DIR
+    ${PROJECT_SOURCE_DIR}/communication_client
+    )
+
+SET(COMMUNICATION_CLIENT_SRC_DIR
+    ${COMMUNICATION_CLIENT_DIR}/src
+    )
+
+SET(COMMUNICATION_CLIENT_INCLUDE_DIR
+    ${COMMUNICATION_CLIENT_DIR}/include
+    )
+
+SET(COMMUNICATION_CLIENT_SOURCES
+    ${COMMUNICATION_CLIENT_SRC_DIR}/SecurityCommunicationClient.cpp
+    ${PROJECT_SOURCE_DIR}/socket_connection/client/SecuritySocketClient.cpp
+    ${PROJECT_SOURCE_DIR}/socket_connection/connection/SocketConnection.cpp
+    ${PROJECT_SOURCE_DIR}/socket_connection/connection/SocketStream.cpp
+    )
+
+SET(COMMUNICATION_CLIENT_INCLUDES
+    ${COMMUNICATION_CLIENT_DEPS_INCLUDE_DIRS}
+    ${COMMUNICATION_CLIENT_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/src/daemon/sockets
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus
+    ${PROJECT_SOURCE_DIR}/src/daemon/socket
+    ${PROJECT_SOURCE_DIR}/src/daemon/socket/api
+    ${PROJECT_SOURCE_DIR}/socket_connection/client
+    ${PROJECT_SOURCE_DIR}/socket_connection/connection
+    )
+
+############################# subdirectories ##################################
+
+ADD_SUBDIRECTORY(commons)
+ADD_SUBDIRECTORY(ace)
+ADD_SUBDIRECTORY(ace_client)
+ADD_SUBDIRECTORY(ace_common)
+ADD_SUBDIRECTORY(ace_install)
+ADD_SUBDIRECTORY(ace_settings)
+ADD_SUBDIRECTORY(ace_popup_validation)
+ADD_SUBDIRECTORY(src)
+ADD_SUBDIRECTORY(build)
+ADD_SUBDIRECTORY(etc)
+#ADD_SUBDIRECTORY(tests)
+IF(ENABLE_WRT_OCSP EQUAL 1)
+ADD_SUBDIRECTORY(wrt_ocsp)
+ENDIF()
+
+####################### systemd files installation ############################
+INSTALL(FILES 
+    ${CMAKE_CURRENT_SOURCE_DIR}/systemd/wrt-security-daemon.service
+    ${CMAKE_CURRENT_SOURCE_DIR}/systemd/wrt-security-daemon.socket 
+    DESTINATION /usr/lib/systemd/system)
diff --git a/LICENSE b/LICENSE
new file mode 100644 (file)
index 0000000..247c97d
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,203 @@
+Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/ace/CMakeLists.txt b/ace/CMakeLists.txt
new file mode 100644 (file)
index 0000000..79bc8b3
--- /dev/null
@@ -0,0 +1,183 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+######################################################################
+
+IF(DEFINED DBUS_CONNECTION)
+#DB vcore
+PKG_CHECK_MODULES(ACE_DB_DEP
+    dpl-efl
+    REQUIRED)
+ENDIF()
+
+#DB ace
+ADD_CUSTOM_COMMAND(
+    OUTPUT ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h
+    COMMAND ${CMAKE_SOURCE_DIR}/ace/orm/gen_db_md5.sh
+    ARGS ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h
+         ${CMAKE_SOURCE_DIR}/ace/orm/ace_db
+    DEPENDS ${CMAKE_SOURCE_DIR}/ace/orm/ace_db
+            ${CMAKE_SOURCE_DIR}/ace/orm/gen_db_md5.sh
+    COMMENT "Generating ACE database checksum"
+    )
+ADD_CUSTOM_TARGET(ACE_DB_CHECKSUM_HEADER DEPENDS ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h)
+
+STRING(REPLACE ";" ":" DEPENDENCIES "${ACE_DB_DEP_INCLUDE_DIRS}")
+
+IF(DEFINED DBUS_CONNECTION)
+ADD_CUSTOM_COMMAND( OUTPUT .ace.db
+  COMMAND rm -f ${CMAKE_CURRENT_BINARY_DIR}/.ace.db
+  COMMAND CPATH=${DEPENDENCIES} gcc -Wall -include ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h -I${PROJECT_SOURCE_DIR}/ace/orm -E ${PROJECT_SOURCE_DIR}/ace/orm/ace_db_sql_generator.h | grep --invert-match "^#" > ${CMAKE_CURRENT_BINARY_DIR}/ace_db.sql
+  COMMAND sqlite3 ${CMAKE_CURRENT_BINARY_DIR}/.ace.db ".read ${CMAKE_CURRENT_BINARY_DIR}/ace_db.sql" || rm -f ${CMAKE_CURRENT_BINARY_DIR}/.ace.db
+  DEPENDS ACE_DB_CHECKSUM_HEADER ${PROJECT_SOURCE_DIR}/ace/orm/ace_db_sql_generator.h ${PROJECT_SOURCE_DIR}/ace/orm/ace_db
+  )
+ELSE()
+ADD_CUSTOM_COMMAND( OUTPUT .ace.db
+  COMMAND rm -f ${CMAKE_CURRENT_BINARY_DIR}/.ace.db
+  COMMAND CPATH=${DEPENDENCIES} gcc -Wall -include ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h -I${PROJECT_SOURCE_DIR}/commons/modules/db/include -I${PROJECT_SOURCE_DIR}/ace/orm -E ${PROJECT_SOURCE_DIR}/ace/orm/ace_db_sql_generator.h | grep --invert-match "^#" > ${CMAKE_CURRENT_BINARY_DIR}/ace_db.sql
+  COMMAND sqlite3 ${CMAKE_CURRENT_BINARY_DIR}/.ace.db ".read ${CMAKE_CURRENT_BINARY_DIR}/ace_db.sql" || rm -f ${CMAKE_CURRENT_BINARY_DIR}/.ace.db
+  DEPENDS ACE_DB_CHECKSUM_HEADER ${PROJECT_SOURCE_DIR}/ace/orm/ace_db_sql_generator.h ${PROJECT_SOURCE_DIR}/ace/orm/ace_db
+  )
+ENDIF()
+
+ADD_CUSTOM_COMMAND( OUTPUT .ace.db-journal
+  COMMAND touch
+  ARGS  ${CMAKE_CURRENT_BINARY_DIR}/.ace.db-journal
+  )
+
+ADD_CUSTOM_TARGET(Sqlite3DbACE ALL DEPENDS .ace.db .ace.db-journal)
+
+INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/ace_db.sql
+    DESTINATION share/wrt-engine/
+    )
+
+###########################################################
+
+INCLUDE(FindPkgConfig)
+
+SET(ACE_TEST_PATH "/usr/apps/org.tizen.policy")
+
+INSTALL(FILES
+    ${CMAKE_CURRENT_SOURCE_DIR}/configuration/bondixml.xsd
+    ${CMAKE_CURRENT_SOURCE_DIR}/configuration/UnrestrictedPolicy.xml
+    ${CMAKE_CURRENT_SOURCE_DIR}/configuration/WAC2.0Policy.xml
+    DESTINATION /usr/etc/ace
+    PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ GROUP_WRITE)
+
+IF(DEFINED DBUS_CONNECTION)
+SET(ACE_LIB_DEPS_BASIC
+    dpl-efl
+    dpl-db-efl
+    dpl-event-efl
+    ecore
+    appcore-efl
+    openssl
+    sqlite3
+    dlog
+    vconf
+    db-util
+    libpcrecpp
+    icu-uc
+    libxml-2.0
+    )
+ELSE()
+SET(ACE_LIB_DEPS_BASIC
+    openssl
+    sqlite3
+    dlog
+    vconf
+    icu-uc
+    libxml-2.0
+    )
+ENDIF()
+
+IF(SMACK_ENABLED)
+    LIST(APPEND ACE_LIB_DEPS_BASIC libprivilege-control)
+ENDIF(SMACK_ENABLED)
+
+PKG_CHECK_MODULES(ACE_LIB_DEPS ${ACE_LIB_DEPS_BASIC} REQUIRED)
+
+SET(WRT_ACE_DIR ${PROJECT_SOURCE_DIR}/ace)
+
+SET(ACE_SOURCES
+  ${WRT_ACE_DIR}/engine/PolicyEvaluator.cpp
+  ${WRT_ACE_DIR}/engine/PolicyInformationPoint.cpp
+  ${WRT_ACE_DIR}/engine/CombinerImpl.cpp
+  ${WRT_ACE_DIR}/engine/parser.cpp
+  ${WRT_ACE_DIR}/engine/PolicyEnforcementPoint.cpp
+  ${WRT_ACE_DIR}/engine/SettingsLogic.cpp
+  ${WRT_ACE_DIR}/engine/Attribute.cpp
+  ${WRT_ACE_DIR}/engine/Condition.cpp
+  ${WRT_ACE_DIR}/engine/Policy.cpp
+  ${WRT_ACE_DIR}/engine/Rule.cpp
+  ${WRT_ACE_DIR}/engine/Subject.cpp
+  ${WRT_ACE_DIR}/engine/TreeNode.cpp
+  ${WRT_ACE_DIR}/engine/ConfigurationManager.cpp
+)
+
+INCLUDE_DIRECTORIES(${ACE_LIB_DEPS_INCLUDE_DIRS})
+INCLUDE_DIRECTORIES(${WRT_ACE_DIR}/include)
+
+IF(NOT DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/db/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    ${PROJECT_SOURCE_DIR}/commons/build/db
+    )
+ENDIF()
+
+SET(WITH_ACE_SETTINGS_SERVER_SOURCES
+   ${WITH_ACE_SETTINGS_SERVER_NONE_SOURCES}
+   )
+
+ADD_LIBRARY(${TARGET_ACE_LIB} SHARED
+    ${ACE_SOURCES}
+    ${WITH_ACE_SETTINGS_SERVER_SOURCES}
+)
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+IF(DEFINED DBUS_CONNECTION)
+TARGET_LINK_LIBRARIES(${TARGET_ACE_LIB}
+    ${TARGET_ACE_DAO_RW_LIB}
+    ${ACE_LIB_DEPS_LIBRARIES}
+    )
+ELSE()
+TARGET_LINK_LIBRARIES(${TARGET_ACE_LIB}
+    ${TARGET_ACE_DAO_RW_LIB}
+    ${ACE_LIB_DEPS_LIBRARIES}
+    libwrt-security-commons
+    libwrt-security-commons-log
+    libwrt-security-commons-db
+    )
+ENDIF()
+
+INSTALL(TARGETS ${TARGET_ACE_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+    include/ace/WRT_INTERFACE.h
+    DESTINATION
+    include/ace
+    )
+
+add_subdirectory(dao)
diff --git a/ace/DESCRIPTION b/ace/DESCRIPTION
new file mode 100644 (file)
index 0000000..aac5ef6
--- /dev/null
@@ -0,0 +1,2 @@
+!!!options!!! stop
+ACE - Access Control Engine - security module for Device APIs
diff --git a/ace/configuration/UnrestrictedPolicy.xml b/ace/configuration/UnrestrictedPolicy.xml
new file mode 100644 (file)
index 0000000..558f2dc
--- /dev/null
@@ -0,0 +1,5 @@
+<policy-set id="Policy-1" combine="first-matching-target">
+    <policy>
+        <rule effect="permit" />
+    </policy>
+</policy-set>
diff --git a/ace/configuration/WAC2.0Policy.xml b/ace/configuration/WAC2.0Policy.xml
new file mode 100644 (file)
index 0000000..c8bd2bb
--- /dev/null
@@ -0,0 +1,175 @@
+<policy-set id="WAC-Policy" combine="first-matching-target">
+    <policy id="WAC-Policy-Trusted" description="WAC's policy for trusted domain" combine="permit-overrides">
+        <target>
+            <subject>
+                <!-- This is finger-print of certificate for WAC Test Widget (operator.root.cert.pem) --> 
+                <subject-match attr="distributor-key-root-fingerprint" func="equal">
+                    sha-1 4A:9D:7A:4B:3B:29:D4:69:0A:70:B3:80:EC:A9:44:6B:03:7C:9A:38
+                </subject-match>
+            </subject>
+            <subject>
+                <!-- This is finger-print of certificate for WAC Publish ID (wac.publisher.pem) --> 
+                <subject-match attr="author-key-root-fingerprint" func="equal">
+                    sha-1 A6:00:BC:53:AC:37:5B:6A:03:C3:7A:8A:E0:1B:87:8B:82:94:9B:C2
+                </subject-match>
+            </subject>
+            <subject>
+                <!-- This is finger-print of certificate for WAC Production (wac.root.production.pem) --> 
+                <subject-match attr="distributor-key-root-fingerprint" func="equal">
+                    sha-1 A0:59:D3:37:E8:C8:2E:7F:38:84:7D:21:A9:9E:19:A9:8E:EC:EB:E1
+                </subject-match>
+            </subject>
+            <subject>
+                <!-- This is finger-print of certificate for WAC Preproduction (wac.root.preproduction.pem) --> 
+                <subject-match attr="distributor-key-root-fingerprint" func="equal">
+                    sha-1 8D:1F:CB:31:68:11:DA:22:59:26:58:13:6C:C6:72:C9:F0:DE:84:2A
+                </subject-match>
+            </subject>
+        </target> 
+
+        <!-- access to external network -->
+        <!--
+        <rule effect="permit">
+            <condition combine="and">
+                <condition combine="or">
+                    <resource-match attr="device-cap" func="equal" match="XMLHttpRequest" />
+                    <resource-match attr="device-cap" func="equal" match="externalNetworkAccess" />
+                    <resource-match attr="device-cap" func="equal" match="messaging.send" />
+                </condition>
+                <environment-match attr="roaming" match="true" />
+            </condition>
+        </rule>
+        -->
+        <rule effect="permit" />
+    </policy>
+
+    <policy id="WAC-Policy-Untrusted" description="WAC's policy for untrusted domain" combine="deny-overrides">
+        <!-- Specific Untrusted Policy for WAC -->
+        <!-- access to accelerometer -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="accelerometer" />
+            </condition>
+        </rule>
+
+        <!-- access to calendar -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="pim.calendar.read" />
+                <resource-match attr="device-cap" func="equal" match="pim.calendar.write" />
+            </condition>
+        </rule>
+
+        <!-- access to camera -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="camera.show" />
+            </condition>
+        </rule>
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="camera.capture" />
+            </condition>
+        </rule>
+
+        <!-- access to contact -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="pim.contact.read" />
+                <resource-match attr="device-cap" func="equal" match="pim.contact.write" />
+            </condition>
+        </rule>
+
+        <!-- access to device-interaction -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="deviceinteraction" />
+            </condition>
+        </rule>
+
+        <!-- access to device-status -->
+        <rule effect="permit">
+             <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="devicestatus.deviceinfo" />
+                <resource-match attr="device-cap" func="equal" match="devicestatus.networkinfo" />
+            </condition>
+        </rule>
+
+        <!-- access to filesystem -->
+        <rule effect="permit">
+            <condition combine="and">
+                <condition combine="or">
+                    <resource-match attr="device-cap" func="equal" match="filesystem.read" />
+                    <resource-match attr="device-cap" func="equal" match="filesystem.write" />
+                </condition>
+                <condition combine="or">
+                    <resource-match attr="param:location" func="equal">wgt-private</resource-match>
+                    <resource-match attr="param:location" func="equal">wgt-private-tmp</resource-match>
+                    <resource-match attr="param:location" func="equal">wgt-package</resource-match>
+                </condition>
+            </condition>
+        </rule>
+
+        <!-- access to messaging -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="messaging.find" />
+                <resource-match attr="device-cap" func="equal" match="messaging.subscribe" />
+                <resource-match attr="device-cap" func="equal" match="messaging.write" />
+            </condition>
+        </rule>
+
+        <!-- access to message send on roaming status -->
+        <!--
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="device-cap" func="equal" match="messaging.send" />
+                <environment-match attr="roaming" match="true" />
+            </condition>
+        </rule>
+        -->
+
+        <!-- access to geolocation -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="geolocation" />
+            </condition>
+        </rule>
+
+        <!-- access to orientation -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="orientation" />
+            </condition>
+        </rule>
+
+        <!-- access to task -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="pim.task.read" />
+                <resource-match attr="device-cap" func="equal" match="pim.task.write" />
+            </condition>
+        </rule>
+        <!-- access to external network -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="XMLHttpRequest" />
+                <resource-match attr="device-cap" func="equal" match="externalNetworkAccess" />
+            </condition>
+        </rule>
+
+        <!-- access to external network on roaming status -->
+        <!--
+        <rule effect="permit">
+            <condition combine="and">
+                <condition combine="or">
+                    <resource-match attr="device-cap" func="equal" match="XMLHttpRequest" />
+                    <resource-match attr="device-cap" func="equal" match="externalNetworkAccess" />
+                </condition>
+                <environment-match attr="roaming" match="true" />
+            </condition>
+        </rule>
+        -->
+
+    </policy>
+</policy-set>
diff --git a/ace/configuration/bondixml.xsd b/ace/configuration/bondixml.xsd
new file mode 100644 (file)
index 0000000..d16a14d
--- /dev/null
@@ -0,0 +1,184 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
+  <xs:element name="policy-set">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element minOccurs="0" ref="target"/>
+        <xs:choice minOccurs="0" maxOccurs="unbounded">
+          <xs:element ref="policy-set"/>
+          <xs:element ref="policy"/>
+        </xs:choice>
+      </xs:sequence>
+      <xs:attributeGroup ref="policy-set.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="policy-set.attlist">
+    <xs:attribute name="combine" default="deny-overrides">
+      <xs:simpleType>
+        <xs:restriction base="xs:token">
+          <xs:enumeration value="deny-overrides"/>
+          <xs:enumeration value="permit-overrides"/>
+          <xs:enumeration value="first-matching-target"/>
+        </xs:restriction>
+      </xs:simpleType>
+    </xs:attribute>
+    <xs:attribute name="id"/>
+  </xs:attributeGroup>
+  <xs:element name="policy">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element minOccurs="0" ref="target"/>
+        <xs:element minOccurs="0" maxOccurs="unbounded" ref="rule"/>
+      </xs:sequence>
+      <xs:attributeGroup ref="policy.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="policy.attlist">
+    <xs:attribute name="combine" default="deny-overrides">
+      <xs:simpleType>
+        <xs:restriction base="xs:token">
+          <xs:enumeration value="deny-overrides"/>
+          <xs:enumeration value="permit-overrides"/>
+          <xs:enumeration value="first-applicable"/>
+        </xs:restriction>
+      </xs:simpleType>
+    </xs:attribute>
+    <xs:attribute name="description"/>
+    <xs:attribute name="id"/>
+  </xs:attributeGroup>
+  <xs:element name="rule">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element minOccurs="0" ref="condition"/>
+      </xs:sequence>
+      <xs:attributeGroup ref="rule.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="rule.attlist">
+    <xs:attribute name="effect" default="permit">
+      <xs:simpleType>
+        <xs:restriction base="xs:token">
+          <xs:enumeration value="permit"/>
+          <xs:enumeration value="prompt-blanket"/>
+          <xs:enumeration value="prompt-session"/>
+          <xs:enumeration value="prompt-oneshot"/>
+          <xs:enumeration value="deny"/>
+        </xs:restriction>
+      </xs:simpleType>
+    </xs:attribute>
+  </xs:attributeGroup>
+  <xs:element name="target">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element maxOccurs="unbounded" ref="subject"/>
+      </xs:sequence>
+    </xs:complexType>
+  </xs:element>
+  <xs:element name="subject">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element maxOccurs="unbounded" ref="subject-match"/>
+      </xs:sequence>
+    </xs:complexType>
+  </xs:element>
+  <xs:element name="condition">
+    <xs:complexType>
+      <xs:choice maxOccurs="unbounded">
+        <xs:element ref="condition"/>
+        <xs:element ref="subject-match"/>
+        <xs:element ref="resource-match"/>
+        <xs:element ref="environment-match"/>
+      </xs:choice>
+      <xs:attributeGroup ref="condition.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="condition.attlist">
+    <xs:attribute name="combine" default="and">
+      <xs:simpleType>
+        <xs:restriction base="xs:token">
+          <xs:enumeration value="and"/>
+          <xs:enumeration value="or"/>
+        </xs:restriction>
+      </xs:simpleType>
+    </xs:attribute>
+  </xs:attributeGroup>
+  <xs:attributeGroup name="match-attrs">
+    <xs:attribute name="attr" use="required"/>
+    <xs:attribute name="match"/>
+    <xs:attribute name="func" default="glob">
+      <xs:simpleType>
+        <xs:restriction base="xs:token">
+          <xs:enumeration value="equal"/>
+          <xs:enumeration value="glob"/>
+          <xs:enumeration value="regexp"/>
+        </xs:restriction>
+      </xs:simpleType>
+    </xs:attribute>
+  </xs:attributeGroup>
+  <xs:element name="subject-match">
+    <xs:complexType mixed="true">
+      <xs:attributeGroup ref="subject-match.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="subject-match.attlist">
+    <xs:attributeGroup ref="match-attrs"/>
+  </xs:attributeGroup>
+  <xs:complexType name="match-model" mixed="true">
+    <xs:choice minOccurs="0" maxOccurs="unbounded">
+      <xs:element ref="subject-attr"/>
+      <xs:element ref="resource-attr"/>
+      <xs:element ref="environment-attr"/>
+    </xs:choice>
+  </xs:complexType>
+  <xs:element name="resource-match">
+    <xs:complexType>
+      <xs:complexContent>
+        <xs:extension base="match-model">
+          <xs:attributeGroup ref="resource-match.attlist"/>
+        </xs:extension>
+      </xs:complexContent>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="resource-match.attlist">
+    <xs:attributeGroup ref="match-attrs"/>
+  </xs:attributeGroup>
+  <xs:element name="environment-match">
+    <xs:complexType>
+      <xs:complexContent>
+        <xs:extension base="match-model">
+          <xs:attributeGroup ref="environment-match.attlist"/>
+        </xs:extension>
+      </xs:complexContent>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="environment-match.attlist">
+    <xs:attributeGroup ref="match-attrs"/>
+  </xs:attributeGroup>
+  <xs:attributeGroup name="attr-attrs">
+    <xs:attribute name="attr" use="required"/>
+  </xs:attributeGroup>
+  <xs:element name="subject-attr">
+    <xs:complexType>
+      <xs:attributeGroup ref="subject-attr.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="subject-attr.attlist">
+    <xs:attributeGroup ref="attr-attrs"/>
+  </xs:attributeGroup>
+  <xs:element name="resource-attr">
+    <xs:complexType>
+      <xs:attributeGroup ref="resource-attr.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="resource-attr.attlist">
+    <xs:attributeGroup ref="attr-attrs"/>
+  </xs:attributeGroup>
+  <xs:element name="environment-attr">
+    <xs:complexType>
+      <xs:attributeGroup ref="environment-attr.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="environment-attr.attlist">
+    <xs:attributeGroup ref="attr-attrs"/>
+  </xs:attributeGroup>
+</xs:schema>
diff --git a/ace/dao/AceDAO.cpp b/ace/dao/AceDAO.cpp
new file mode 100644 (file)
index 0000000..e7d8c6f
--- /dev/null
@@ -0,0 +1,474 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       AceDAO.cpp
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#include <ace-dao-rw/AceDAO.h>
+
+#include <openssl/md5.h>
+#include <dpl/foreach.h>
+#include <dpl/string.h>
+#include <dpl/log/log.h>
+#include <dpl/db/orm.h>
+#include <ace-dao-ro/AceDAOUtilities.h>
+#include <ace-dao-ro/AceDAOConversions.h>
+#include <ace-dao-ro/AceDatabase.h>
+
+using namespace DPL::DB::ORM;
+using namespace DPL::DB::ORM::ace;
+using namespace AceDB::AceDaoUtilities;
+using namespace AceDB::AceDaoConversions;
+
+namespace {
+char const * const EMPTY_SESSION = "";
+} // namespace
+
+namespace AceDB{
+
+void AceDAO::setPromptDecision(
+    WidgetHandle widgetHandle,
+    int ruleId,
+    const boost::optional<DPL::String> &session,
+    PromptDecision decision)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+
+        ACE_DB_DELETE(del, AcePromptDecision, &AceDaoUtilities::m_databaseInterface);
+        del->Where(
+            And(
+                Equals<AcePromptDecision::app_id>(widgetHandle),
+                Equals<AcePromptDecision::rule_id>(ruleId)));
+        del->Execute();
+
+        AcePromptDecision::Row row;
+        row.Set_rule_id(ruleId);
+        row.Set_decision(promptDecisionToInt(decision));
+        row.Set_app_id(widgetHandle);
+        row.Set_session(session);
+        ACE_DB_INSERT(insert, AcePromptDecision, &AceDaoUtilities::m_databaseInterface);
+        insert->Values(row);
+        insert->Execute();
+
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to setUserSetting");
+    }
+}
+
+void AceDAO::removePolicyResult(
+        const BaseAttributeSet &attributes)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+
+        auto attrHash =  convertToHash(attributes);
+
+        ACE_DB_DELETE(del,
+                      AcePolicyResult,
+                      &AceDaoUtilities::m_databaseInterface);
+        del->Where(Equals<AcePolicyResult::hash>(attrHash));
+        del->Execute();
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to removeVerdict");
+    }
+}
+
+void AceDAO::clearAllSettings(void)
+{
+    clearWidgetDevCapSettings();
+    clearDevCapSettings();
+}
+
+void AceDAO::setDevCapSetting(const std::string &resource,
+                              PreferenceTypes preference)
+{
+    Try {
+        ACE_DB_UPDATE(update, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row row;
+        row.Set_general_setting(preferenceToInt(preference));
+        update->Values(row);
+        update->Where(
+            Equals<AceDevCap::id_uri>(DPL::FromUTF8String(resource)));
+        update->Execute();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to SetResourceSetting");
+    }
+}
+
+void AceDAO::removeDevCapSetting(const std::string &resource)
+{
+    Try {
+        ACE_DB_UPDATE(update, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row row;
+        row.Set_general_setting(preferenceToInt(PreferenceTypes::PREFERENCE_DEFAULT));
+        update->Values(row);
+        update->Where(
+            Equals<AceDevCap::id_uri>(DPL::FromUTF8String(resource)));
+        update->Execute();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to removeResourceSetting");
+    }
+}
+
+
+void AceDAO::setWidgetDevCapSetting(const std::string &resource,
+                                    WidgetHandle handler,
+                                    PreferenceTypes preference)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        // TODO JOIN
+        AceDevCap::Row rrow;
+        if (!getResourceByUri(resource, rrow)) {
+            ThrowMsg(Exception::DatabaseError, "Resource not found");
+        }
+
+        ACE_DB_INSERT(insert,
+                      AceWidgetDevCapSetting,
+                      &AceDaoUtilities::m_databaseInterface);
+
+        AceWidgetDevCapSetting::Row row;
+        row.Set_app_id(handler);
+        int rid = rrow.Get_resource_id();
+        row.Set_resource_id(rid);
+        row.Set_access_value(preferenceToInt(preference));
+        insert->Values(row);
+        insert->Execute();
+
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to setUserSetting");
+    }
+}
+
+void AceDAO::removeWidgetDevCapSetting(const std::string &resource,
+                                       WidgetHandle handler)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row rrow;
+        if (!getResourceByUri(resource, rrow)) {
+            ThrowMsg(Exception::DatabaseError, "resource not found");
+        }
+
+        ACE_DB_DELETE(del,
+                      AceWidgetDevCapSetting,
+                      &AceDaoUtilities::m_databaseInterface);
+
+        Equals<AceWidgetDevCapSetting::app_id> e1(handler);
+        Equals<AceWidgetDevCapSetting::resource_id> e2(rrow.Get_resource_id());
+        del->Where(And(e1, e2));
+        del->Execute();
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to clearUserSettings");
+    }
+}
+
+
+void AceDAO::setPolicyResult(const BaseAttributeSet &attributes,
+                             const ExtendedPolicyResult &exResult)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+
+        // TODO: this call is connected with logic.
+        // It should be moved to PolicyEvaluator
+        addAttributes(attributes);
+
+        auto attrHash = convertToHash(attributes);
+
+        ACE_DB_DELETE(del, AcePolicyResult, &AceDaoUtilities::m_databaseInterface)
+        del->Where(Equals<AcePolicyResult::hash>(attrHash));
+        del->Execute();
+
+        ACE_DB_INSERT(insert, AcePolicyResult, &AceDaoUtilities::m_databaseInterface);
+        AcePolicyResult::Row row;
+        row.Set_decision(PolicyResult::serialize(exResult.policyResult));
+        row.Set_hash(attrHash);
+        row.Set_rule_id(exResult.ruleId);
+        insert->Values(row);
+        insert->Execute();
+
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to addVerdict");
+    }
+}
+
+void AceDAO::resetDatabase(void)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        ACE_DB_DELETE(del1, AcePolicyResult, &AceDaoUtilities::m_databaseInterface);
+        del1->Execute();
+        ACE_DB_DELETE(del2, AceWidgetDevCapSetting, &AceDaoUtilities::m_databaseInterface);
+        del2->Execute();
+        ACE_DB_DELETE(del3, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        del3->Execute();
+        ACE_DB_DELETE(del4, AceSubject, &AceDaoUtilities::m_databaseInterface);
+        del4->Execute();
+        ACE_DB_DELETE(del5, AceAttribute, &AceDaoUtilities::m_databaseInterface);
+        del5->Execute();
+        ACE_DB_DELETE(del6, AcePromptDecision, &AceDaoUtilities::m_databaseInterface);
+        del6->Execute();
+
+        transaction.Commit();
+
+        // TODO there is no such query yet in ORM.
+        //        GlobalConnection::DataCommandAutoPtr command =
+        //                GlobalConnectionSingleton::Instance().PrepareDataCommand(
+        //                        "VACUUM");
+        //        command->Step();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to resetDatabase");
+    }
+}
+
+void AceDAO::clearPolicyCache(void)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        ACE_DB_DELETE(del1, AcePolicyResult, &AceDaoUtilities::m_databaseInterface);
+        del1->Execute();
+        ACE_DB_DELETE(del2, AceAttribute, &AceDaoUtilities::m_databaseInterface);
+        del2->Execute();
+        ACE_DB_DELETE(del3, AcePromptDecision, &AceDaoUtilities::m_databaseInterface);
+        del3->Execute();
+
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to clearPolicyCache");
+    }
+}
+
+void AceDAO::clearDevCapSettings()
+{
+    Try {
+        ACE_DB_UPDATE(update, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row row;
+        row.Set_general_setting(-1);
+        update->Values(row);
+        update->Execute();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to clearResourceSettings");
+    }
+}
+
+void AceDAO::clearWidgetDevCapSettings()
+{
+    Try {
+        ACE_DB_DELETE(del, AceWidgetDevCapSetting, &AceDaoUtilities::m_databaseInterface);
+        del->Execute();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to clearUserSettings");
+    }
+}
+
+int AceDAO::addResource(const std::string &request)
+{
+    LogDebug("addResource: " << request);
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row rrow;
+        if (getResourceByUri(request, rrow)) {
+            transaction.Commit();
+            return rrow.Get_resource_id();
+        }
+
+        ACE_DB_INSERT(insert, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row row;
+        row.Set_id_uri(DPL::FromUTF8String(request));
+        row.Set_general_setting(-1);
+        insert->Values(row);
+        int id = insert->Execute();
+        transaction.Commit();
+        return id;
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in addResource");
+    }
+}
+
+void AceDAO::addAttributes(const BaseAttributeSet &attributes)
+{
+    Try {
+        BaseAttributeSet::const_iterator iter;
+
+        for (iter = attributes.begin(); iter != attributes.end(); ++iter) {
+            ACE_DB_SELECT(select, AceAttribute, &AceDaoUtilities::m_databaseInterface);
+            select->Where(Equals<AceAttribute::name>(DPL::FromUTF8String(
+                *(*iter)->getName())));
+            std::list<AceAttribute::Row> rows = select->GetRowList();
+            if (!rows.empty()) {
+                continue;
+            }
+
+            ACE_DB_INSERT(insert, AceAttribute, &AceDaoUtilities::m_databaseInterface);
+            AceAttribute::Row row;
+            row.Set_name(DPL::FromUTF8String(*(*iter)->getName()));
+            row.Set_type(attributeTypeToInt((*iter)->getType()));
+            insert->Values(row);
+            insert->Execute();
+        }
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in addAttributes");
+    }
+}
+
+void AceDAO::setRequestedDevCaps(
+    WidgetHandle widgetHandle,
+    const RequestedDevCapsMap &permissions)
+{
+    Try {
+        FOREACH(it, permissions) {
+          ACE_DB_INSERT(insert, AceRequestedDevCaps,
+                        &AceDaoUtilities::m_databaseInterface);
+          AceRequestedDevCaps::Row row;
+          row.Set_app_id(widgetHandle);
+          row.Set_dev_cap(it->first);
+          row.Set_grant_smack(it->second ? 1 : 0);
+          insert->Values(row);
+          insert->Execute();
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in setStaticDevCapPermissions");
+    }
+}
+
+void AceDAO::removeRequestedDevCaps(
+    WidgetHandle widgetHandle)
+{
+    Try {
+        ACE_DB_DELETE(del, AceRequestedDevCaps,
+                      &AceDaoUtilities::m_databaseInterface);
+        del->Where(Equals<AceRequestedDevCaps::app_id>(widgetHandle));
+        del->Execute();
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in removeRequestedDevCaps");
+    }
+}
+
+void AceDAO::setAcceptedFeature(
+    WidgetHandle widgetHandle,
+    const FeatureNameVector &vector)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        FOREACH(it, vector) {
+            ACE_DB_INSERT(insert, AceAcceptedFeature,
+                          &AceDaoUtilities::m_databaseInterface);
+            AceAcceptedFeature::Row row;
+            row.Set_app_id(widgetHandle);
+            row.Set_feature(*it);
+            insert->Values(row);
+            insert->Execute();
+        }
+        transaction.Commit();
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in setAcceptedFeature");
+    }
+}
+
+void AceDAO::removeAcceptedFeature(
+    WidgetHandle widgetHandle)
+{
+    Try
+    {
+        ACE_DB_DELETE(del, AceAcceptedFeature,
+                      &AceDaoUtilities::m_databaseInterface);
+        del->Where(Equals<AceAcceptedFeature::app_id>(widgetHandle));
+        del->Execute();
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in removeAcceptedFeature");
+    }
+}
+
+void AceDAO::registerWidgetInfo(WidgetHandle handle,
+                                const WidgetRegisterInfo& info,
+                                const WidgetCertificateDataList& dataList)
+{
+    Try
+    {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+
+        ACE_DB_INSERT(insert, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        WidgetInfo::Row wi;
+        wi.Set_app_id(handle);
+        wi.Set_widget_type(static_cast<int>(info.type));
+        wi.Set_widget_id(info.widget_id);
+        wi.Set_widget_version(info.version);
+        wi.Set_author_name(info.authorName);
+        wi.Set_share_href(info.shareHref);
+        insert->Values(wi);
+        insert->Execute();
+
+        WidgetCertificateDataList::const_iterator it;
+        for (it = dataList.begin(); it != dataList.end(); ++it)
+        {
+            WidgetCertificateFingerprint::Row wcf;
+            wcf.Set_app_id(handle);
+            wcf.Set_owner(it->owner);
+            wcf.Set_chainid(it->chainId);
+            wcf.Set_type(it->type);
+            wcf.Set_md5_fingerprint(DPL::FromUTF8String(it->strMD5Fingerprint));
+            wcf.Set_sha1_fingerprint(DPL::FromUTF8String(it->strSHA1Fingerprint));
+            wcf.Set_common_name(it->strCommonName);
+            ACE_DB_INSERT(insert, WidgetCertificateFingerprint, &AceDaoUtilities::m_databaseInterface);
+            insert->Values(wcf);
+            insert->Execute();
+        }
+        transaction.Commit();
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in registerWidgetInfo");
+    }
+}
+
+void AceDAO::unregisterWidgetInfo(WidgetHandle handle)
+{
+    if(AceDAO::isWidgetInstalled(handle)) {
+        Try
+        {
+            ACE_DB_DELETE(del, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+            del->Where(Equals<WidgetInfo::app_id>(handle));
+            del->Execute();
+        } Catch(DPL::DB::SqlConnection::Exception::Base) {
+            ReThrowMsg(Exception::DatabaseError, "Failed in unregisterWidgetInfo");
+        }
+    }
+}
+
+}
diff --git a/ace/dao/AceDAOConversions.cpp b/ace/dao/AceDAOConversions.cpp
new file mode 100644 (file)
index 0000000..d4ccf8e
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       AceDaoConversions.h
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#include <openssl/md5.h>
+#include <dpl/foreach.h>
+
+#include <ace-dao-ro/AceDAOConversions.h>
+
+namespace AceDB {
+
+DPL::String AceDaoConversions::convertToHash(const BaseAttributeSet &attributes)
+{
+    unsigned char attrHash[MD5_DIGEST_LENGTH];
+    std::string attrString;
+    FOREACH(it, attributes) {
+        // [CR] implementation of it->toString() is not secure, 24.03.2010
+        attrString.append((*it)->toString());
+    }
+
+    MD5((unsigned char *) attrString.c_str(), attrString.length(), attrHash);
+
+    char attrHashCoded[MD5_DIGEST_LENGTH*2 + 1];
+    for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
+        snprintf(&attrHashCoded[i << 1], 3,
+                "%02X",
+                static_cast<int>(attrHash[i]));
+    }
+    return DPL::FromASCIIString(attrHashCoded);
+}
+
+
+}
diff --git a/ace/dao/AceDAOReadOnly.cpp b/ace/dao/AceDAOReadOnly.cpp
new file mode 100644 (file)
index 0000000..09795b7
--- /dev/null
@@ -0,0 +1,570 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       AceDAOReadOnlyReadOnly.cpp
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#include <list>
+#include <utility>
+#include <dpl/optional_typedefs.h>
+#include <ace-dao-ro/AceDAOReadOnly.h>
+#include <ace-dao-ro/AceDAOUtilities.h>
+#include <ace-dao-ro/AceDAOConversions.h>
+#include <ace-dao-ro/AceDatabase.h>
+#include <dpl/foreach.h>
+
+using namespace DPL::DB::ORM;
+using namespace DPL::DB::ORM::ace;
+using namespace AceDB::AceDaoUtilities;
+using namespace AceDB::AceDaoConversions;
+
+namespace AceDB {
+
+static const int DB_ALLOW_ALWAYS = 0;
+static const int DB_ALLOW_FOR_SESSION = 1;
+static const int DB_ALLOW_THIS_TIME = 2;
+static const int DB_DENY_ALWAYS = 3;
+static const int DB_DENY_FOR_SESSION = 4;
+static const int DB_DENY_THIS_TIME = 5;
+
+static const int DB_APP_UNKNOWN = 0;
+static const int DB_APP_WAC20 = 1;
+static const int DB_APP_TIZEN = 2;
+
+int AceDAOReadOnly::promptDecisionToInt(PromptDecision decision)
+{
+    if (PromptDecision::ALLOW_ALWAYS == decision) {
+        return DB_ALLOW_ALWAYS;
+    } else if (PromptDecision::DENY_ALWAYS == decision) {
+        return DB_DENY_ALWAYS;
+    } else if (PromptDecision::ALLOW_THIS_TIME == decision) {
+        return DB_ALLOW_THIS_TIME;
+    } else if (PromptDecision::DENY_THIS_TIME == decision) {
+        return DB_DENY_THIS_TIME;
+    } else if (PromptDecision::ALLOW_FOR_SESSION == decision) {
+        return DB_ALLOW_FOR_SESSION;
+    }
+    // DENY_FOR_SESSION
+    return DB_DENY_FOR_SESSION;
+}
+
+PromptDecision AceDAOReadOnly::intToPromptDecision(int dec) {
+    if (dec == DB_ALLOW_ALWAYS) {
+        return PromptDecision::ALLOW_ALWAYS;
+    } else if (dec == DB_DENY_ALWAYS) {
+        return PromptDecision::DENY_ALWAYS;
+    } else if (dec == DB_ALLOW_THIS_TIME) {
+        return PromptDecision::ALLOW_THIS_TIME;
+    } else if (dec == DB_DENY_THIS_TIME) {
+        return PromptDecision::DENY_THIS_TIME;
+    } else if (dec == DB_ALLOW_FOR_SESSION) {
+        return PromptDecision::ALLOW_FOR_SESSION;
+    }
+    // DB_DENY_FOR_SESSION
+    return PromptDecision::DENY_FOR_SESSION;
+}
+
+int AceDAOReadOnly::appTypeToInt(AppTypes app_type)
+{
+    switch (app_type) {
+    case AppTypes::Unknown:
+        return DB_APP_UNKNOWN;
+    case AppTypes::WAC20:
+        return DB_APP_WAC20;
+    case AppTypes::Tizen:
+        return DB_APP_TIZEN;
+    default:
+        return DB_APP_UNKNOWN;
+    }
+
+}
+
+AppTypes AceDAOReadOnly::intToAppType(int app_type)
+{
+    switch (app_type) {
+    case DB_APP_UNKNOWN:
+        return AppTypes::Unknown;
+    case DB_APP_WAC20:
+        return AppTypes::WAC20;
+    case DB_APP_TIZEN:
+        return AppTypes::Tizen;
+    default:
+        return AppTypes::Unknown;
+    }
+}
+
+void AceDAOReadOnly::attachToThreadRO()
+{
+    AceDaoUtilities::m_databaseInterface.AttachToThread(
+        DPL::DB::SqlConnection::Flag::RO);
+}
+
+void AceDAOReadOnly::attachToThreadRW()
+{
+    AceDaoUtilities::m_databaseInterface.AttachToThread(
+        DPL::DB::SqlConnection::Flag::RW);
+}
+
+void AceDAOReadOnly::detachFromThread()
+{
+    AceDaoUtilities::m_databaseInterface.DetachFromThread();
+}
+
+OptionalCachedPromptDecision AceDAOReadOnly::getPromptDecision(
+    WidgetHandle widgetHandle,
+    int ruleId)
+{
+    Try {
+        // get matching subject verdict
+        ACE_DB_SELECT(select, AcePromptDecision, &AceDaoUtilities::m_databaseInterface);
+
+        select->Where(
+            And(
+                Equals<AcePromptDecision::rule_id>(ruleId),
+                Equals<AcePromptDecision::app_id>(widgetHandle)));
+
+        std::list<AcePromptDecision::Row> rows = select->GetRowList();
+        if (rows.empty()) {
+            return OptionalCachedPromptDecision();
+        }
+
+        AcePromptDecision::Row row = rows.front();
+        CachedPromptDecision decision;
+        decision.decision = intToPromptDecision(row.Get_decision());
+        decision.session = row.Get_session();
+
+        return OptionalCachedPromptDecision(decision);
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getPromptDecision");
+    }
+}
+
+void AceDAOReadOnly::getAttributes(BaseAttributeSet *attributes)
+{
+    if (NULL == attributes) {
+        LogError("NULL pointer");
+        return;
+    }
+    attributes->clear();
+    std::string aname;
+    int type;
+    Try {
+        ACE_DB_SELECT(select, AceAttribute, &AceDaoUtilities::m_databaseInterface);
+        typedef std::list<AceAttribute::Row> RowList;
+        RowList list = select->GetRowList();
+
+        FOREACH(i, list) {
+            BaseAttributePtr attribute(new BaseAttribute());
+            DPL::String name = i->Get_name();
+            aname = DPL::ToUTF8String(name);
+            type = i->Get_type();
+
+            attribute->setName(&aname);
+            attribute->setType(intToAttributeType(type));
+            attributes->insert(attribute);
+        }
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getAttributes");
+    }
+}
+
+OptionalExtendedPolicyResult AceDAOReadOnly::getPolicyResult(
+        const BaseAttributeSet &attributes)
+{
+
+    auto attrHash = convertToHash(attributes);
+    return getPolicyResult(attrHash);
+}
+
+OptionalExtendedPolicyResult AceDAOReadOnly::getPolicyResult(
+    const DPL::String &attrHash)
+{
+    Try {
+        // get matching subject verdict
+        ACE_DB_SELECT(select, AcePolicyResult, &AceDaoUtilities::m_databaseInterface);
+        Equals<AcePolicyResult::hash> e1(attrHash);
+        select->Where(e1);
+
+        std::list<AcePolicyResult::Row> rows = select->GetRowList();
+        if (rows.empty()) {
+            return OptionalExtendedPolicyResult();
+        }
+
+        AcePolicyResult::Row row = rows.front();
+        int decision = row.Get_decision();
+        ExtendedPolicyResult res;
+        res.policyResult = PolicyResult::deserialize(decision);
+        res.ruleId = row.Get_rule_id();
+        return OptionalExtendedPolicyResult(res);
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getVerdict");
+    }
+}
+
+PreferenceTypes AceDAOReadOnly::getDevCapSetting(const std::string &resource)
+{
+    Try {
+        AceDevCap::Row row;
+        if (!getResourceByUri(resource, row)) {
+            return PreferenceTypes::PREFERENCE_DEFAULT;
+        }
+        return intToPreference(row.Get_general_setting());
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getResourceSetting");
+    }
+}
+
+void AceDAOReadOnly::getDevCapSettings(PreferenceTypesMap *globalSettingsMap)
+{
+    if (NULL == globalSettingsMap) {
+        LogError("Null pointer");
+        return;
+    }
+    globalSettingsMap->clear();
+    Try {
+        ACE_DB_SELECT(select, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        typedef std::list<AceDevCap::Row> RowList;
+        RowList list = select->GetRowList();
+
+        FOREACH(i, list) {
+            PreferenceTypes p = intToPreference(i->Get_general_setting());
+            globalSettingsMap->insert(make_pair(DPL::ToUTF8String(
+                i->Get_id_uri()), p));
+        }
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getResourceSettings");
+    }
+}
+
+void AceDAOReadOnly::getWidgetDevCapSettings(BasePermissionList *outputList)
+{
+    if (NULL == outputList) {
+        LogError("NULL pointer");
+        return;
+    }
+    outputList->clear();
+    Try {
+        std::string resourceName;
+        PreferenceTypes allowAccess;
+
+        ACE_DB_SELECT(select,
+                      AceWidgetDevCapSetting,
+                      &AceDaoUtilities::m_databaseInterface);
+
+        typedef std::list<AceWidgetDevCapSetting::Row> RowList;
+        RowList list = select->GetRowList();
+
+        // TODO JOIN
+        FOREACH(i, list) {
+            int app_id = i->Get_app_id();
+            int res_id = i->Get_resource_id();
+
+            ACE_DB_SELECT(resourceSelect, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+            resourceSelect->Where(Equals<AceDevCap::resource_id>(res_id));
+            AceDevCap::Row rrow = resourceSelect->GetSingleRow();
+
+            resourceName = DPL::ToUTF8String(rrow.Get_id_uri());
+
+            if (!resourceName.empty()) {
+                allowAccess = intToPreference(i->Get_access_value());
+                outputList->push_back(
+                    BasePermission(app_id,
+                    resourceName,
+                    allowAccess));
+            }
+        }
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to findUserSettings");
+    }
+}
+
+PreferenceTypes AceDAOReadOnly::getWidgetDevCapSetting(
+        const std::string &resource,
+        WidgetHandle handler)
+{
+    Try {
+        AceDevCap::Row rrow;
+        if (!getResourceByUri(resource, rrow)) {
+            return PreferenceTypes::PREFERENCE_DEFAULT;
+        }
+        int resourceId = rrow.Get_resource_id();
+
+        // get matching user setting
+        ACE_DB_SELECT(select, AceWidgetDevCapSetting, &AceDaoUtilities::m_databaseInterface);
+
+        select->Where(And(Equals<AceWidgetDevCapSetting::resource_id>(resourceId),
+                Equals<AceWidgetDevCapSetting::app_id>(handler)));
+
+        std::list<int> values =
+            select->GetValueList<AceWidgetDevCapSetting::access_value>();
+        if (values.empty()) {
+            return PreferenceTypes::PREFERENCE_DEFAULT;
+        }
+        return intToPreference(values.front());
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in getUserSetting");
+    }
+}
+
+void AceDAOReadOnly::getRequestedDevCaps(
+    WidgetHandle widgetHandle,
+    RequestedDevCapsMap *permissions)
+{
+    if (NULL == permissions) {
+        LogError("NULL pointer");
+        return;
+    }
+    permissions->clear();
+    Try {
+        ACE_DB_SELECT(select, AceRequestedDevCaps,
+                      &AceDaoUtilities::m_databaseInterface);
+        select->Where(
+            Equals<AceRequestedDevCaps::app_id>(widgetHandle));
+        std::list<AceRequestedDevCaps::Row> list = select->GetRowList();
+
+        FOREACH(i, list) {
+            permissions->insert(std::make_pair(i->Get_dev_cap(),
+                   i->Get_grant_smack() == 1));
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getRequestedDevCaps");
+    }
+}
+
+void AceDAOReadOnly::getAcceptedFeature(
+    WidgetHandle widgetHandle,
+    FeatureNameVector *fvector)
+{
+    if (NULL == fvector) {
+        LogError("NULL pointer");
+        return;
+    }
+
+    fvector->clear();
+    Try {
+        ACE_DB_SELECT(select, AceAcceptedFeature,
+                      &AceDaoUtilities::m_databaseInterface);
+        select->Where(
+            Equals<AceAcceptedFeature::app_id>(widgetHandle));
+        std::list<AceAcceptedFeature::Row> list = select->GetRowList();
+
+        FOREACH(i, list) {
+            fvector->push_back(i->Get_feature());
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getRequestedDevCaps");
+    }
+}
+
+AppTypes AceDAOReadOnly::getWidgetType(WidgetHandle handle)
+{
+    Try {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(handle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+        DPL::OptionalInt res;
+        if (!rows.empty()) {
+            res = rows.front().Get_widget_type();
+            AppTypes retType = (!res ? AppTypes::Unknown : static_cast<AppTypes>(*res));
+            return retType;
+        } else {
+            LogDebug("Can not find widget type");
+            return AppTypes::Unknown;
+        }
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getWidgetType");
+    }
+}
+
+std::string AceDAOReadOnly::getVersion(WidgetHandle widgetHandle)
+{
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(widgetHandle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+        DPL::OptionalString res;
+        if(!rows.empty()) {
+            res = rows.front().Get_widget_version();
+            return (!res ? "" : DPL::ToUTF8String(*res));
+        } else {
+            LogDebug("Widget not installed");
+            return "";
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getVersion");
+    }
+}
+
+std::string AceDAOReadOnly::getAuthorName(WidgetHandle widgetHandle)
+{
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(widgetHandle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+        DPL::OptionalString res;
+        if(!rows.empty()) {
+            res = rows.front().Get_author_name();
+            return (!res ? "" : DPL::ToUTF8String(*res));
+        } else {
+            LogDebug("Widget not installed");
+            return "";
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getAuthorName");
+    }
+}
+
+std::string AceDAOReadOnly::getGUID(WidgetHandle widgetHandle)
+{
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(widgetHandle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+        DPL::OptionalString res;
+        if(!rows.empty()) {
+            res = rows.front().Get_widget_id();
+            return (!res ? "" : DPL::ToUTF8String(*res));
+        } else {
+            LogDebug("Widget not installed");
+            return "";
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getGUID");
+    }
+}
+
+WidgetCertificateCNList AceDAOReadOnly::getKeyCommonNameList(
+        WidgetHandle widgetHandle,
+        WidgetCertificateData::Owner owner,
+        WidgetCertificateData::Type type)
+{
+    Try {
+        ACE_DB_SELECT(select, WidgetCertificateFingerprint, &AceDaoUtilities::m_databaseInterface);
+        select->Where(And(And(
+            Equals<WidgetCertificateFingerprint::app_id>(widgetHandle),
+            Equals<WidgetCertificateFingerprint::owner>(owner)),
+            Equals<WidgetCertificateFingerprint::type>(type)));
+        WidgetCertificateFingerprint::Select::RowList rows = select->GetRowList();
+
+        WidgetCertificateCNList out;
+        FOREACH(it, rows)
+        {
+            DPL::OptionalString cn = it->Get_common_name();
+            out.push_back(!cn ? "" : DPL::ToUTF8String(*cn));
+        }
+        return out;
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getKeyCommonNameList");
+    }
+}
+
+FingerPrintList AceDAOReadOnly::getKeyFingerprints(
+        WidgetHandle widgetHandle,
+        WidgetCertificateData::Owner owner,
+        WidgetCertificateData::Type type)
+{
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetCertificateFingerprint, &AceDaoUtilities::m_databaseInterface);
+        select->Where(And(And(
+            Equals<WidgetCertificateFingerprint::app_id>(widgetHandle),
+            Equals<WidgetCertificateFingerprint::owner>(owner)),
+            Equals<WidgetCertificateFingerprint::type>(type)));
+        WidgetCertificateFingerprint::Select::RowList rows = select->GetRowList();
+
+        FingerPrintList keys;
+        FOREACH(it, rows)
+        {
+            DPL::OptionalString sha1 = it->Get_sha1_fingerprint();
+            if (!!sha1)
+                keys.push_back(DPL::ToUTF8String(*sha1));
+            DPL::OptionalString md5 = it->Get_md5_fingerprint();
+            if (!!md5)
+                keys.push_back(DPL::ToUTF8String(*md5));
+        }
+        return keys;
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getKeyFingerprints");
+    }
+}
+
+std::string AceDAOReadOnly::getShareHref(WidgetHandle widgetHandle)
+{
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(widgetHandle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+
+        if(rows.empty())
+            ThrowMsg(Exception::DatabaseError, "Cannot find widget. Handle: " << widgetHandle);
+
+        DPL::OptionalString value = rows.front().Get_share_href();
+        std::string ret = "";
+        if(!!value)
+            ret = DPL::ToUTF8String(*value);
+        return ret;
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getShareHref");
+    }
+}
+
+WidgetHandleList AceDAOReadOnly::getHandleList()
+{
+    LogDebug("Getting DbWidgetHandle List");
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        return select->GetValueList<WidgetInfo::app_id>();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to list of widget handles");
+    }
+}
+
+bool AceDAOReadOnly::isWidgetInstalled(WidgetHandle handle)
+{
+    Try {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(handle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+        return !rows.empty() ? true : false;
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in isWidgetInstalled");
+    }
+}
+
+}
diff --git a/ace/dao/AceDAOUtilities.cpp b/ace/dao/AceDAOUtilities.cpp
new file mode 100644 (file)
index 0000000..4d5292e
--- /dev/null
@@ -0,0 +1,193 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       AceDaoReadOnly.h
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#include <openssl/md5.h>
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+
+#include <ace-dao-ro/AceDatabase.h>
+#include <ace-dao-ro/AceDAOUtilities.h>
+#include <ace-dao-ro/AceDAOReadOnly.h>
+
+namespace AceDB {
+
+namespace {
+const char* ACE_DB_DATABASE = "/opt/dbspace/.ace.db";
+DPL::DB::SqlConnection::Flag::Type ACE_DB_FLAGS =
+    DPL::DB::SqlConnection::Flag::UseLucene;
+}
+
+DPL::DB::ThreadDatabaseSupport AceDaoUtilities::m_databaseInterface(
+        ACE_DB_DATABASE, ACE_DB_FLAGS);
+
+BaseAttribute::Type AceDaoUtilities::intToAttributeType(int val)
+{
+    switch (val) {
+    case 0:
+        return BaseAttribute::Type::Subject;
+    case 1:
+        return BaseAttribute::Type::Environment;
+    case 2:
+        return BaseAttribute::Type::Resource;
+    case 3:
+        return BaseAttribute::Type::FunctionParam;
+    case 4:
+        return BaseAttribute::Type::WidgetParam;
+
+    default:
+        Assert(0 && "Unknown Attribute type value");
+        return BaseAttribute::Type::Subject; //remove compilation warrning
+    }
+}
+
+int AceDaoUtilities::attributeTypeToInt(BaseAttribute::Type type)
+{
+    // we cannot cast enum -> int because this cast will be removed from next c++ standard
+    switch (type) {
+    case BaseAttribute::Type::Subject:
+        return 0;
+    case BaseAttribute::Type::Environment:
+        return 1;
+    case BaseAttribute::Type::Resource:
+        return 2;
+    case BaseAttribute::Type::FunctionParam:
+        return 3;
+    case BaseAttribute::Type::WidgetParam:
+        return 4;
+
+    default:
+        Assert(0 && "Unknown Attribute type!");
+        return 0; //remove compilation warrning
+    }
+}
+
+int AceDaoUtilities::preferenceToInt(PreferenceTypes p)
+{
+    switch (p) {
+        case PreferenceTypes::PREFERENCE_PERMIT:
+        return 1;
+    case PreferenceTypes::PREFERENCE_DENY:
+        return 0;
+    case PreferenceTypes::PREFERENCE_BLANKET_PROMPT:
+        return 2;
+    case PreferenceTypes::PREFERENCE_SESSION_PROMPT:
+        return 3;
+    case PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT:
+        return 4;
+
+    default:
+        return -1;
+    }
+}
+
+PreferenceTypes AceDaoUtilities::intToPreference(int p)
+{
+    switch (p) {
+    case 1:
+        return PreferenceTypes::PREFERENCE_PERMIT;
+    case 0:
+        return PreferenceTypes::PREFERENCE_DENY;
+    case 2:
+        return PreferenceTypes::PREFERENCE_BLANKET_PROMPT;
+    case 3:
+        return PreferenceTypes::PREFERENCE_SESSION_PROMPT;
+    case 4:
+        return PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT;
+
+    default:
+        return PreferenceTypes::PREFERENCE_DEFAULT;
+    }
+}
+
+VerdictTypes AceDaoUtilities::intToVerdict(int v)
+{
+    switch (v) {
+    case -1:
+        return VerdictTypes::VERDICT_UNKNOWN;
+    case 0:
+        return VerdictTypes::VERDICT_DENY;
+    case 1:
+        return VerdictTypes::VERDICT_PERMIT;
+    case 2:
+        return VerdictTypes::VERDICT_INAPPLICABLE;
+
+    default:
+        Assert(0 && "Cannot convert int to verdict");
+        return VerdictTypes::VERDICT_UNKNOWN; // remove compile warrning
+    }
+}
+
+int AceDaoUtilities::verdictToInt(VerdictTypes v)
+{
+    switch (v) {
+    case VerdictTypes::VERDICT_UNKNOWN:
+        return -1;
+    case VerdictTypes::VERDICT_DENY:
+        return 0;
+    case VerdictTypes::VERDICT_PERMIT:
+        return 1;
+    case VerdictTypes::VERDICT_INAPPLICABLE:
+        return 2;
+
+    default:
+        Assert(0 && "Unknown Verdict value");
+        return -1; // remove compile warrning
+    }
+}
+
+bool AceDaoUtilities::getSubjectByUri(const std::string &uri,
+                                      DPL::DB::ORM::ace::AceSubject::Row &row)
+{
+    using namespace DPL::DB::ORM;
+    using namespace DPL::DB::ORM::ace;
+    ACE_DB_SELECT(select, AceSubject, &m_databaseInterface);
+    select->Where(Equals<AceSubject::id_uri>(DPL::FromUTF8String(uri)));
+    std::list<AceSubject::Row> rows = select->GetRowList();
+    if (rows.empty()) {
+        return false;
+    }
+
+    row = rows.front();
+    return true;
+}
+
+bool AceDaoUtilities::getResourceByUri(const std::string &uri,
+                                       DPL::DB::ORM::ace::AceDevCap::Row &row)
+{
+    using namespace DPL::DB::ORM;
+    using namespace DPL::DB::ORM::ace;
+    ACE_DB_SELECT(select, AceDevCap, &m_databaseInterface);
+    select->Where(Equals<AceDevCap::id_uri>(DPL::FromUTF8String(uri)));
+    std::list<AceDevCap::Row> rows = select->GetRowList();
+    if (rows.empty()) {
+        return false;
+    }
+
+    row = rows.front();
+    return true;
+}
+
+
+}
diff --git a/ace/dao/AceDatabase.cpp b/ace/dao/AceDatabase.cpp
new file mode 100644 (file)
index 0000000..6c91951
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    AceDatabase.cpp
+ * @author  Lukasz Marek (l.marek@samsung.com)
+ * @version 1.0
+ * @brief   This file contains the declaration of ace database
+ */
+
+#include <ace-dao-ro/AceDatabase.h>
+
+DPL::Mutex g_aceDbQueriesMutex;
diff --git a/ace/dao/BaseAttribute.cpp b/ace/dao/BaseAttribute.cpp
new file mode 100644 (file)
index 0000000..e15785c
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       BaseAttribute.cpp
+ * @author     Lukasz Marek (l.marek@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#include <sstream>
+#include <string>
+
+#include <ace-dao-ro/BaseAttribute.h>
+
+namespace AceDB {
+
+const char* BaseAttribute::typeToString(Type type)
+{
+    const char * ret = NULL;
+    switch (type) {
+    case Type::Resource:
+        ret = "resource";
+        break;
+    case Type::Subject:
+        ret = "subject";
+        break;
+    case Type::Environment:
+        ret = "environment";
+        break;
+    default:
+        ret = "unknown type";
+        break;
+    }
+
+    return ret;
+}
+
+std::string BaseAttribute::toString() const
+{
+    std::string ret;
+    const char * SEPARATOR = ";";
+
+    ret.append(m_name);
+    ret.append(SEPARATOR);
+    ret.append(typeToString(m_typeId));
+    ret.append(SEPARATOR);
+    if (m_undetermindState) {
+        ret.append("true");
+    } else {
+        ret.append("false");
+    }
+    ret.append(SEPARATOR);
+    for (std::list<std::string>::const_iterator it = value.begin();
+         it != value.end();
+         ++it) {
+        std::stringstream num;
+        num << it->size();
+        ret.append(num.str());
+        ret.append(SEPARATOR);
+        ret.append(*it);
+        ret.append(SEPARATOR);
+    }
+
+    return ret;
+}
+
+}
diff --git a/ace/dao/CMakeLists.txt b/ace/dao/CMakeLists.txt
new file mode 100644 (file)
index 0000000..f106b3c
--- /dev/null
@@ -0,0 +1,114 @@
+
+IF(DEFINED DBUS_CONNECTION)
+SET(ACE_DAO_DEPS_LIST
+    dpl-efl
+    dpl-db-efl
+    ecore
+    appcore-efl
+    openssl
+    vconf
+    db-util
+    libpcrecpp
+    icu-uc
+    libxml-2.0
+    )
+ELSE()
+SET(ACE_DAO_DEPS_LIST
+    openssl
+    db-util
+    libpcrecpp
+    icu-uc
+    libxml-2.0
+    )
+ENDIF()
+
+PKG_CHECK_MODULES(ACE_DAO_DEPS ${ACE_DAO_DEPS_LIST} REQUIRED)
+
+set(ACE_SRC_DIR ${PROJECT_SOURCE_DIR}/ace/dao)
+
+set(ACE_DAO_RO_SOURCES
+    ${ACE_SRC_DIR}/AceDAOReadOnly.cpp
+    ${ACE_SRC_DIR}/AceDAOUtilities.cpp
+    ${ACE_SRC_DIR}/AceDAOConversions.cpp
+    ${ACE_SRC_DIR}/BaseAttribute.cpp
+    ${ACE_SRC_DIR}/AceDatabase.cpp
+    ${ACE_SRC_DIR}/PromptModel.cpp
+)
+
+set(ACE_DAO_RW_SOURCES
+    ${ACE_SRC_DIR}/AceDAO.cpp
+)
+
+INCLUDE_DIRECTORIES(${ACE_SRC_DIR})
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/ace/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/ace/orm)
+INCLUDE_DIRECTORIES(${ACE_DAO_DEPS_INCLUDE_DIRS})
+IF(NOT DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/db/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/db
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    )
+ENDIF()
+
+ADD_LIBRARY(${TARGET_ACE_DAO_RO_LIB} SHARED
+    ${ACE_DAO_RO_SOURCES}
+)
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RO_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RO_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RO_LIB} PROPERTIES
+    COMPILE_FLAGS "-include ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h")
+
+IF(DEFINED DBUS_CONNECTION)
+target_link_libraries(${TARGET_ACE_DAO_RO_LIB}
+    ${TARGET_DPL_EFL}
+    ${TARGET_DPL_DB_EFL}
+    ${ACE_DAO_DEPS_LIBRARY}
+    ${ACE_DAO_DEPS_LDFLAGS}
+    )
+ELSE()
+target_link_libraries(${TARGET_ACE_DAO_RO_LIB}
+    ${ACE_DAO_DEPS_LIBRARY}
+    ${ACE_DAO_DEPS_LDFLAGS}
+    libwrt-security-commons
+    libwrt-security-commons-db
+    libwrt-security-commons-log
+    )
+ENDIF()
+
+ADD_LIBRARY(${TARGET_ACE_DAO_RW_LIB} SHARED
+    ${ACE_DAO_RW_SOURCES}
+)
+SET_SOURCE_FILES_PROPERTIES(${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h PROPERTIES GENERATED 1)
+ADD_DEPENDENCIES(${TARGET_ACE_DAO_RO_LIB} ACE_DB_CHECKSUM_HEADER)
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RW_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RW_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RW_LIB} PROPERTIES
+    COMPILE_FLAGS "-include ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h")
+
+target_link_libraries(${TARGET_ACE_DAO_RW_LIB}
+    ${ACE_DAO_DEPS_LIST_LIBRARIES}
+    ${TARGET_ACE_DAO_RO_LIB}
+)
+
+INSTALL(TARGETS ${TARGET_ACE_DAO_RO_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(TARGETS ${TARGET_ACE_DAO_RW_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
diff --git a/ace/dao/PromptModel.cpp b/ace/dao/PromptModel.cpp
new file mode 100644 (file)
index 0000000..ee2a133
--- /dev/null
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/* @file        PromptModel.cpp
+ * @author      Justyna Mejzner (j.kwiatkowsk@samsung.com)
+ * @author      Jaroslaw Osmanski (j.osmanski@samsung.com)
+ * @version     1.0
+ *
+ */
+
+#include <ace-dao-ro/PromptModel.h>
+
+#include <algorithm>
+#include <dpl/log/log.h>
+#include <dpl/assert.h>
+
+namespace {
+
+const char INFO[] = "Widget requires access to:";
+const char DENY[] = "Deny";
+const char ALLOW[] = "Permit";
+
+const char BLANKET_CHECKBOX_LABEL[] = "Keep setting as permanent";
+const char SESSION_CHECKBOX_LABEL[] = "Remember for one run";
+
+Prompt::ButtonLabels aceQuestionLabel = {DENY, ALLOW};
+
+static Prompt::PromptLabels* getModel(
+        Prompt::PromptModel::PromptType promptType,
+        const std::string& resourceId)
+{
+    std::string strLabel;
+    strLabel = INFO;
+    strLabel += "<br>";
+    strLabel += resourceId;
+
+    return new Prompt::PromptLabels(promptType, aceQuestionLabel, strLabel);
+}
+
+Prompt::Validity fromPromptTypeToValidity(int aPromptType, bool checkClicked)
+{
+    using namespace Prompt;
+    PromptModel::PromptType promptTypeEnum =
+        static_cast<PromptModel::PromptType>(aPromptType);
+    switch (promptTypeEnum) {
+    case PromptModel::PROMPT_ONESHOT:
+        return Validity::ONCE;
+    case PromptModel::PROMPT_SESSION:
+        if (checkClicked)
+        {
+            return Validity::SESSION;
+        }
+        else
+        {
+            return Validity::ONCE;
+        }
+    case PromptModel::PROMPT_BLANKET:
+        if (checkClicked)
+        {
+            return Validity::ALWAYS;
+        }
+        else
+        {
+            return Validity::ONCE;
+        }
+    default:
+        Assert(0);
+        return Validity::ONCE;
+    }
+}
+} // namespace anonymous
+
+namespace Prompt {
+
+
+PromptLabels::PromptLabels(int promptType,
+                           const Prompt::ButtonLabels& questionLabel,
+                           const std::string& mainLabel) :
+               m_promptType(promptType),
+               m_buttonLabels(questionLabel),
+               m_mainLabel(mainLabel)
+{
+
+}
+
+int PromptLabels::getPromptType() const
+{
+    return m_promptType;
+}
+const ButtonLabels& PromptLabels::getButtonLabels() const
+{
+    return m_buttonLabels;
+}
+const std::string& PromptLabels::getMainLabel() const
+{
+    return m_mainLabel;
+}
+
+DPL::OptionalString PromptLabels::getCheckLabel() const
+{
+    if (PromptModel::PROMPT_BLANKET == m_promptType)
+    {
+        return DPL::OptionalString(
+                DPL::FromUTF8String(BLANKET_CHECKBOX_LABEL));
+    }
+    else if (PromptModel::PROMPT_SESSION == m_promptType)
+    {
+        return DPL::OptionalString(
+                DPL::FromUTF8String(SESSION_CHECKBOX_LABEL));
+    }
+
+    return DPL::OptionalString();
+}
+
+bool PromptLabels::isAllowed(const size_t buttonClicked) const
+{
+    Assert(buttonClicked < aceQuestionLabel.size() &&
+            "Button Clicked number is not in range of questionLabel");
+
+    return aceQuestionLabel[buttonClicked] == ALLOW;
+}
+
+PromptAnswer::PromptAnswer(bool isAccessAllowed, Validity validity) :
+        m_isAccessAllowed(isAccessAllowed),
+        m_validity(validity)
+{
+
+}
+
+PromptAnswer::PromptAnswer(
+        int aPromptType, unsigned int buttonAns, bool checkAns)
+{
+    Assert(buttonAns < aceQuestionLabel.size() &&
+            "Button Clicked number is not in range of questionLabel");
+
+    m_isAccessAllowed = aceQuestionLabel[buttonAns] == ALLOW;
+    m_validity = fromPromptTypeToValidity(aPromptType, checkAns);
+}
+
+bool PromptAnswer::isAccessAllowed() const
+{
+    return m_isAccessAllowed;
+}
+
+Validity PromptAnswer::getValidity() const
+{
+    return m_validity;
+}
+
+PromptLabels* PromptModel::getOneShotModel(const std::string& resourceId)
+{
+    return getModel(PROMPT_ONESHOT, resourceId);
+}
+
+PromptLabels* PromptModel::getSessionModel(const std::string& resourceId)
+{
+    return getModel(PROMPT_SESSION, resourceId);
+}
+
+PromptLabels* PromptModel::getBlanketModel(const std::string& resourceId)
+{
+    return getModel(PROMPT_BLANKET, resourceId);
+}
+
+
+} // Prompt
diff --git a/ace/engine/Attribute.cpp b/ace/engine/Attribute.cpp
new file mode 100644 (file)
index 0000000..bc96a2b
--- /dev/null
@@ -0,0 +1,892 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+#include <fnmatch.h>
+#include <pcrecpp.h>
+#include <sstream>
+#include <dpl/foreach.h>
+#include <dpl/log/log.h>
+#include <ace/Attribute.h>
+
+const bool Attribute::alpha[256] = {
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
+    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
+};
+const bool Attribute::digit[256] = {
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0
+};
+
+const bool Attribute::mark[256] = {
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0
+};
+
+bool Attribute::searchAndCut(const char *str)
+{
+    //TODO
+    size_t pos = m_name.rfind(str);
+    if (pos == std::string::npos) {
+        return false;
+    }
+    if ((strlen(str) + pos) == m_name.size()) {
+        m_name.erase(pos, std::string::npos);
+        return true;
+    }
+    return false;
+}
+
+Attribute::Attribute(const std::string *name,
+                     const Match matchFunc,
+                     const Type type_) :
+    matchFunction(matchFunc)
+{
+    m_name = *name;
+    m_typeId = type_;
+    m_undetermindState = false;
+    if (matchFunction != Match::Equal
+        && matchFunction != Match::Glob
+        && matchFunction != Match::Regexp)
+    {
+        //LogDebug("MID: " << matchFunction);
+        Assert(0 && "Match function problem");
+    }
+
+    if (searchAndCut(".scheme")) {
+        modifierFunction = Modifier::Scheme;
+    } else if (searchAndCut(".authority")) {
+        modifierFunction = Modifier::Authority;
+    } else if (searchAndCut(".scheme-authority")) {
+        modifierFunction = Modifier::SchemeAuthority;
+    } else if (searchAndCut(".host")) {
+        modifierFunction = Modifier::Host;
+    } else if (searchAndCut(".path")) {
+        modifierFunction = Modifier::Path;
+    } else {
+        modifierFunction = Modifier::Non;
+    }
+}
+
+static Attribute::MatchResult equal_comparator(const std::string *first,
+                                               const std::string *second)
+{
+    if((*first) == (*second)) {
+        return Attribute::MatchResult::MRTrue;
+    }
+    return  Attribute::MatchResult::MRFalse;
+}
+
+static Attribute::MatchResult glob_comparator(const std::string *first,
+        const std::string *second)
+{
+    // order is important
+    if (!fnmatch(first->c_str(), second->c_str(), 0)) {
+        return Attribute::MatchResult::MRTrue;
+    }
+    return  Attribute::MatchResult::MRFalse;
+}
+
+static Attribute::MatchResult regexp_comparator(const std::string *first,
+                                                const std::string *second)
+{
+    // order is important
+    pcrecpp::RE re(first->c_str());
+    if (re.FullMatch(second->c_str())) {
+        return Attribute::MatchResult::MRTrue;
+    }
+    return  Attribute::MatchResult::MRFalse;
+}
+
+Attribute::MatchResult Attribute::lists_comparator(
+        const std::list<std::string> *first,
+        const std::list<std::string> *second,
+        Attribute::MatchResult (*comparator)(const std::string *,
+                                             const std::string *)) const
+{
+    //NOTE: BONDI defines all availabe matching function as: if some string from first input bag
+    //matches some input string from second input bag, so it's required to find only one matching string
+    MatchResult result = MatchResult::MRFalse;
+
+    for (std::list<std::string>::const_iterator second_iter = second->begin();
+         (second_iter != second->end()) && (result != MatchResult::MRTrue);
+         ++second_iter)
+    {
+        std::string *modified_value = applyModifierFunction(&(*second_iter));
+        //Value was not an URI, it will be removed from the string bag (ignored)
+        if (modified_value == NULL) {
+            continue;
+        }
+
+        for (std::list<std::string>::const_iterator first_iter = first->begin();
+             first_iter != first->end();
+             ++first_iter) {
+            //Compare attributes
+            if ((*comparator)(&(*first_iter), modified_value) == MatchResult::MRTrue) {
+                result = MatchResult::MRTrue;
+                break; //Only one match is enough
+            }
+        }
+        if (modified_value) {
+            delete modified_value;
+            modified_value = NULL;
+        }
+    }
+
+    if (result == MatchResult::MRTrue) {
+        LogDebug("Returning TRUE");
+#ifdef ALL_LOGS
+    } else if (result == MatchResult::MRFalse) {
+        LogDebug("Returning FALSE");
+    } else if (result == MatchResult::MRUndetermined) {
+        LogDebug("Returning UNDETERMINED");
+#endif
+    }
+
+    return result;
+}
+
+std::string * Attribute::applyModifierFunction(const std::string * val) const
+{
+    std::string * result = NULL;
+    switch (modifierFunction) {
+    case Modifier::Scheme:
+        result = uriScheme(val);
+        break;
+    case Modifier::Authority:
+        result = uriAuthority(val);
+        break;
+    case Modifier::SchemeAuthority:
+        result = uriSchemeAuthority(val);
+        break;
+    case Modifier::Host:
+        result = uriHost(val);
+        break;
+    case Modifier::Path:
+        result = uriPath(val);
+        break;
+    default:
+        result = new std::string(*val);
+    }
+
+    return result;
+}
+
+/**
+ * this - attribute obtained from xmlPolicy tree
+ * attribute - attribute obtained from PIP
+ */
+Attribute::MatchResult Attribute::matchAttributes(
+        const BaseAttribute *attribute) const
+{
+    std::string tempNam = *(attribute->getName());
+    std::string tempVal;
+    std::string myVal;
+
+    if (!(attribute->getValue()->empty())) {
+        tempVal = attribute->getValue()->front();
+    }
+
+    if (!(this->value.empty())) {
+        myVal = this->value.front();
+    }
+
+#ifdef ALL_LOGS
+    LogDebug("Comparing attribute: " << this->m_name << "(" <<
+        myVal << ") with: " << tempNam <<
+        "(" << tempVal << ")");
+#endif
+    Assert(
+        (this->m_name == *(attribute->getName())) &&
+        "Two completely different attributes are being compared!");
+    Assert(
+        (this->m_typeId == attribute->getType()) &&
+        "Two completely different attributes are being compared!");
+
+    if (attribute->isUndetermind()) {
+        LogDebug("Attribute match undetermined");
+        return MatchResult::MRUndetermined;
+    }
+
+    //Regardles the algorithm used, if we have empty
+    //bag the result is always false
+    if (this->isValueEmpty() || attribute->isValueEmpty()) {
+        if (this->isValueEmpty()) {
+            LogDebug("empty bag in condition comparing");
+        }
+        if (attribute->isValueEmpty()) {
+            LogDebug("empty bag in attribute comparing");
+        }
+        return MatchResult::MRFalse;
+    }
+
+    if (this->matchFunction == Match::Equal) {
+        return lists_comparator(&(this->value),
+                                attribute->getValue(),
+                                equal_comparator);
+    } else if (this->matchFunction == Match::Glob) {
+        return lists_comparator(&(this->value),
+                                attribute->getValue(),
+                                glob_comparator);
+    } else if (this->matchFunction == Match::Regexp) {
+        return lists_comparator(&(this->value),
+                                attribute->getValue(),
+                                regexp_comparator);
+    }        //[CR] Change to Assert
+    Assert(false && " ** Critical :: no match function selected!");
+    return MatchResult::MRFalse; // to remove compilator warning
+}
+
+void Attribute::addValue(const std::string *val)
+{
+    this->getValue()->push_back(*val);
+}
+
+std::ostream & operator<<(std::ostream & out,
+                          const Attribute & attr)
+{
+    out << "attr: m_name: " << *(attr.getName())
+        << " type: " << Attribute::typeToString(attr.getType())
+        << " value: ";
+    if (attr.m_undetermindState) {
+        out << "Undetermined";
+    } else if (attr.getValue()->empty()) {
+        out << "Empty string bag";
+    } else {
+        FOREACH (it, *attr.getValue()) {
+            out << *it;
+        }
+    }
+    return out;
+}
+
+bool
+Attribute::parse(const std::string *input,
+                 std::string *val) const
+{
+    static const char *pattern =
+        "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
+    pcrecpp::RE re(pattern);
+    if (!re.FullMatch(input->c_str(), &val[0], &val[1],
+                 &val[2], &val[3], &val[4],
+                 &val[5], &val[6], &val[7], &val[8])) {
+        LogDebug("Error: attribute parsing failed.");
+        return false;
+    }
+#ifdef ALL_LOGS
+    for (int i = 0; i < 9; i++) {
+        LogDebug("val " << i << " :" << val[i]);
+    }
+#endif
+
+    if (find_error(val)) {
+        LogDebug("Input is not an URI " << *input);
+        for (int i = 0; i < 9; ++i) {
+            val[i].clear();
+        }
+        return false;
+    }
+
+    return true;
+}
+
+Attribute::~Attribute()
+{
+}
+
+std::string * Attribute::uriScheme(const std::string *input) const
+{
+    std::string part[9];
+    if (!parse(input, part)) {
+        return NULL;
+    }
+    return new string(part[1]);
+}
+
+std::string *
+Attribute::uriAuthority(const std::string *input) const
+{
+    std::string part[9];
+    if (!parse(input, part)) {
+        return NULL;
+    }
+    return new string(part[3]);
+}
+
+std::string *
+Attribute::uriSchemeAuthority(const std::string *input) const
+{
+    std::string part[9];
+    if (!parse(input, part)) {
+        return NULL;
+    }
+
+    if (part[0].size() == 0 || part[2].size() == 0) {
+        return new std::string();
+    }
+    return new string(part[0] + part[2]);
+}
+
+std::string *
+Attribute::uriHost(const std::string *input) const
+{
+    std::string part[9];
+    if (!parse(input, part)) {
+        return NULL;
+    }
+    return getHost(&(part[3]));
+}
+
+std::string *
+Attribute::uriPath(const std::string *input) const
+{
+    //TODO right now uriPath leaves leading '/' in uri, this slash is removed from the string
+    //it's not clear if leading '/' is a part of path component or only the separator
+    std::string part[9];
+    if (!parse(input, part)) {
+        return NULL;
+    }
+
+    std::string * temp = NULL;
+
+    if (part[4].at(0) == '/') {
+        temp = new string(part[4].substr(1, part[4].length() - 1));
+    } else {
+        temp = new string(part[4]);
+    }
+
+    return temp;
+}
+
+bool Attribute::find_error(const std::string *tab) const
+{
+    //We are checking tab[1] which contains scheme without ':' at the end
+    if (!checkScheme(&(tab[1]))) {
+        LogDebug("Check scheme failed, URI is invalid");
+        return true; //error found
+    }
+    if (!checkAuthority(&(tab[3]))) {
+        LogDebug("Check authority failed, URI is invalid");
+        return true; //error found
+    }
+
+    if (!checkPath(&(tab[4]))) {
+        LogDebug("Check path failed, URI is invalid");
+        return true; //error found
+    }
+
+    return false;
+}
+
+bool Attribute::checkScheme(const std::string *part) const
+{
+    Assert(part != NULL && "Checking NULLable string. This should never happen");
+
+    bool result = true;
+
+    //TODO change part->at to data=part->c_str()
+    //TODO can scheme be empty? In absolute URI no, in relative URI yes
+    if (part->empty()) {
+        //Empty string is a correct schema
+        result = true;
+    } else if (alpha[(int) (part->at(0))] == 0) {
+        result = false; // First scheme character must be alpha
+    } else {
+        // rest must be alpha or digit or '+' or '-' or '.'
+        for (unsigned int i = 1; i < part->size(); ++i) {
+            int c = static_cast<int>(part->at(i));
+            if (!isSchemeAllowedCharacter(c)) {
+                result = false;
+                break;
+            }
+        }
+    }
+    return result;
+}
+
+bool Attribute::checkAuthority(const std::string *part) const
+{
+    Assert(part != NULL && "Checking NULLable string. This should never happen");
+
+    //Server is a subset of reg_m_names so here we only check if authority matches reg_m_name
+    //Additional check if authority is a valid 'server' component is done in getHost
+    if (part->empty()) {
+        return true; //empty authority is valid uri
+    }
+    bool result = true;
+
+    const char * data = part->c_str();
+    for (size_t i = 0; i < part->length(); ++i) {
+        int c = (int) data[i];
+        if (isUnreserved(c)) {
+            continue;
+        }
+        if (c == '$') {
+            continue;
+        }
+        if (c == ',') {
+            continue;
+        }
+        if (c == ';') {
+            continue;
+        }
+        if (c == ':') {
+            continue;
+        }
+        if (c == '@') {
+            continue;
+        }
+        if (c == '&') {
+            continue;
+        }
+        if (c == '=') {
+            continue;
+        }
+        if (c == '+') {
+            continue;
+        }
+        if (c == '%') {
+            if (isEscaped(data + i)) {
+                i += 2; //rewind the two escaped characters
+                continue;
+            }
+        }
+        result = false;
+        break;
+    }
+
+    return result;
+}
+
+std::string * Attribute::getHost(const std::string *part) const
+{
+    if (part->empty()) {
+        return new std::string("");
+    }
+
+    //Check userinfo
+    size_t userInfoPos = part->find("@");
+    if (userInfoPos != std::string::npos) {
+        std::string data = part->substr(0, userInfoPos);
+        if (!isUserInfoAllowedString(&data)) {
+            return new string(""); //the authority is not composed of 'server'  part
+        }
+    }
+
+    std::string host;
+    //If we use host modifier then authority is composed of 'server' part so
+    //the port must contain only digits
+    size_t portPos = part->find(":");
+    if (portPos != std::string::npos) {
+        for (unsigned int i = portPos + 1; i < part->size(); ++i) {
+            if (!digit[(int) part->at(i)]) {
+                return new string(""); //the authority is not composed of 'server'  part
+            }
+        }
+        host = part->substr(userInfoPos + 1, portPos - (userInfoPos + 1));
+    } else {
+        host = part->substr(userInfoPos + 1, part->length() - (userInfoPos + 1));
+    }
+
+    if (!isHostAllowedString(&host)) {
+        //Even if the string is not allowed for host this can still be a valid uri
+        return new string("");
+    }
+
+    return new std::string(host);
+}
+
+bool Attribute::checkPath(const std::string *part) const
+{
+    bool result = true;
+
+    const char * data = part->c_str();
+
+    for (unsigned int i = 0; i < part->size(); ++i) {
+        int c = data[i];
+        if (c == '/') {
+            //If we found slash then the next character must be a part of segment
+            //It cannot be '/' so we have to check it immediately
+            i++;
+            c = data[i];
+            if (!isSegmentAllowedCharacter(c)) {
+                result = false;
+                break;
+            }
+        } else if (c == ';') {
+            //Start param part of segment
+            i++; //Param can be empty so we don't have to check what's right after semicolon
+            continue;
+        } else if (c == '%') {
+            //We have to handle escaped characters differently than other segment allowed characters
+            //because we need an array
+            if (isEscaped(data + i)) {
+                i += 2;
+            } else {
+                result = false;
+                break;
+            }
+        } else {
+            if (!isSegmentAllowedCharacter(c)) {
+                result = false;
+                break;
+            }
+        }
+    }
+
+    return result;
+}
+
+bool Attribute::isSchemeAllowedCharacter(int c) const
+{
+    bool result = false;
+    if (isAlphanum(c)) {
+        result = true;
+    } else if (c == '+') {
+        result = true;
+    } else if (c == '-') {
+        result = true;
+    } else if (c == '.') {
+        result = true;
+    }
+
+    return result;
+}
+
+bool Attribute::isSegmentAllowedCharacter(int c) const
+{
+    bool result = true;
+
+    //    LogDebug("Checking is segment allowed for char "<<(char)c);
+
+    if (isUnreserved(c)) { //do nothing, result = true
+    } else if (c == ':') { //do nothing, result = true
+    } else if (c == '@') { //do nothing, result = true
+    } else if (c == '&') { //do nothing, result = true
+    } else if (c == '=') { //do nothing, result = true
+    } else if (c == '+') { //do nothing, result = true
+    } else if (c == '$') { //do nothing, result = true
+    } else if (c == ',') { //do nothing, result = true
+    } else {
+        result = false;
+    }
+
+    return result;
+}
+
+bool Attribute::isUserInfoAllowedString(const std::string * str) const
+{
+    bool result = false;
+
+    const char * data = str->c_str();
+
+    for (unsigned int i = 0; i < str->length(); ++i) {
+        int c = data[i];
+        if (isUnreserved(c)) {
+            result = true;
+        } else if (c == '%') {
+            //isEsacped method checks if we don't cross array bounds, so we can
+            //safely give data[i] here
+            result = isEscaped((data + i));
+            if (result == false) {
+                break;
+            }
+            i += 2; //rewind the next two characters sEsacped method checks if we don't cross array bounds, so we can safely rewind
+        } else if (c == ',') {
+            result = true;
+        } else if (c == '$') {
+            result = true;
+        } else if (c == '+') {
+            result = true;
+        } else if (c == '=') {
+            result = true;
+        } else if (c == '&') {
+            result = true;
+        } else if (c == '@') {
+            result = true;
+        } else if (c == ':') {
+            result = true;
+        }
+    }
+    return result;
+}
+
+bool Attribute::isUnreserved(int c) const
+{
+    return isAlphanum(c) || mark[c];
+}
+
+bool Attribute::isAlphanum(int c) const
+{
+    return alpha[c] || digit[c];
+}
+
+bool Attribute::isHex(int c) const
+{
+    bool result = false;
+
+    if (digit[c]) {
+        result = true;
+    } else if (c == 'A') {
+        result = true;
+    } else if (c == 'B') {
+        result = true;
+    } else if (c == 'C') {
+        result = true;
+    } else if (c == 'D') {
+        result = true;
+    } else if (c == 'E') {
+        result = true;
+    } else if (c == 'F') {
+        result = true;
+    } else if (c == 'a') {
+        result = true;
+    } else if (c == 'b') {
+        result = true;
+    } else if (c == 'c') {
+        result = true;
+    } else if (c == 'd') {
+        result = true;
+    } else if (c == 'e') {
+        result = true;
+    } else if (c == 'f') {
+        result = true;
+    }
+
+    return result;
+}
+
+bool Attribute::isEscaped(const char esc[3]) const
+{
+    if (esc == NULL) {
+        return false;
+    }
+
+    if ((esc[0] == 0) || (esc[1] == 0) || (esc[2] == 0)) {
+        //We get an array that seems to be out of bounds.
+        //To be on the safe side return here
+        LogDebug("HEX NULLS");
+        return false;
+    }
+
+    if (esc[0] != '%') {
+        LogDebug(
+            "Error: first character of escaped value must be a precent but is "
+            <<
+            esc[0]);
+        return false;
+    }
+
+#ifdef ALL_LOGS
+    for (int i = 0; i < 3; i++) {
+        LogDebug("HEX " << esc[i]);
+    }
+#endif
+    return isHex((int) esc[1]) && isHex((int) esc[2]);
+}
+
+bool Attribute::isHostAllowedString(const std::string * str) const
+{
+    bool result = true;
+
+    if (digit[(int) str->at(0)]) {
+        //IPv4 address
+        result = isIPv4AllowedString(str);
+    } else {
+        //Hostname
+        result = isHostNameAllowedString(str);
+    }
+
+    return result;
+}
+
+bool Attribute::isIPv4AllowedString(const std::string * str) const
+{
+    LogDebug("Is hostIPv4 allowed String for " << *str);
+
+    const char * data = str->c_str();
+    bool result = true;
+    int digitCounter = 0;
+    int dotCounter = 0;
+
+    for (unsigned int i = 0; i < str->length(); ++i) {
+        if (data[i] == '.') {
+            dotCounter++;
+            digitCounter = 0;
+        } else if (digit[(int) data[i]]) {
+            digitCounter++;
+            if ((digitCounter > 3) || !digitCounter) {
+                result = false;
+                break;
+            }
+        } else {
+            result = false;
+            break;
+        }
+    }
+    if (dotCounter != 3) {
+        result = false;
+    }
+    return result;
+}
+
+bool Attribute::isHostNameAllowedString(const std::string * str) const
+{
+    LogDebug("Is hostname allowed String for " << *str);
+
+    int lastPosition = 0; //the position of last dot + 1
+    const char * data = str->c_str();
+    bool finalDot = false;
+    size_t end = str->length();
+    bool result = false;
+
+    for (size_t i = 0; i < end; ++i) {
+        if (data[i] == '.') {
+            if (i == str->length() - 1) { //ending dot
+                //There can be a leading '.' int the hostm_name
+                finalDot = true;
+                break;
+            } else {
+                //we found domain label
+                if (!isDomainLabelAllowedString(data + lastPosition, i -
+                                                lastPosition)) {
+                    result = false;
+                    goto end;
+                }
+                lastPosition = i + 1; //Set position to position of last dot + 1
+            }
+        }
+    }
+
+    if (finalDot) {
+        //we have to rewind one position to check the rightmost string
+        //but only in case we find final dot
+        end--;
+    }
+    //Compare only the rightmost string aaa.bbbb.rightmostString.
+    result = isTopLabelAllowedString(data + lastPosition, end - lastPosition);
+
+end:
+
+    if (result) {
+        LogInfo("Hostname is allowed");
+    } else {
+        LogInfo("Hostname is NOT allowed");
+    }
+
+    return result;
+}
+
+bool Attribute::isDomainLabelAllowedString(const char * data,
+        int length) const
+{
+    LogDebug(
+        "Is domain allowed String for " << data << " taking first " <<
+        length <<
+        " chars");
+
+    if (!isAlphanum((int) data[0]) || !isAlphanum((int) data[length - 1])) {
+        return false;
+    }
+
+    for (int i = 0; i < length; i++) {
+        if ((!isAlphanum(data[i])) && !(data[i] == '-')) {
+            return false;
+        }
+    }
+    return true;
+}
+
+bool Attribute::isTopLabelAllowedString(const char * data,
+        int length) const
+{
+    if ((!alpha[(int) data[0]]) || (!isAlphanum((int) data[length - 1]))) {
+        return false;
+    }
+
+    for (int i = 1; i < length - 1; i++) {
+        if ((!isAlphanum(data[i])) && !(data[i] == '-')) {
+            return false;
+        }
+    }
+    return true;
+}
+
+void printAttributes(const AttributeSet& attrs)
+{
+    if (attrs.empty()) {
+        LogWarning("Empty attribute set");
+    } else {
+        LogDebug("PRINT ATTRIBUTES:");
+        for (AttributeSet::const_iterator it = attrs.begin();
+             it != attrs.end();
+             ++it)
+        {
+            LogDebug("name: " << *(*it)->getName());
+        }
+    }
+}
+
+void printAttributes(const std::list<Attribute> & attrs)
+{
+    if (attrs.empty()) {
+        LogWarning("Empty attribute set");
+    } else {
+        LogDebug("PRINT ATTRIBUTES:");
+        for (std::list<Attribute>::const_iterator it = attrs.begin();
+             it != attrs.end();
+             ++it
+             ) {
+            LogDebug(*it);
+        }
+    }
+}
+
+//KW const char * matchResultToString(Attribute::MatchResult result){
+//KW
+//KW     const char * ret = NULL;
+//KW
+//KW     switch(result){
+//KW
+//KW         case Attribute::MRTrue:
+//KW             ret = "true";
+//KW             break;
+//KW         case Attribute::MRFalse:
+//KW             ret = "false";
+//KW            break;
+//KW         case Attribute::MRUndetermined:
+//KW             ret = "undetermined";
+//KW             break;
+//KW         default:
+//KW             ret = "Wrong match result";
+//KW     }
+//KW
+//KW     return ret;
+//KW
+//KW }
diff --git a/ace/engine/CombinerImpl.cpp b/ace/engine/CombinerImpl.cpp
new file mode 100644 (file)
index 0000000..dab775f
--- /dev/null
@@ -0,0 +1,334 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : CombinerImpl.cpp
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#include <dpl/log/log.h>
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+
+#include <ace/CombinerImpl.h>
+#include <ace/Rule.h>
+#include <ace/Policy.h>
+
+namespace {
+
+bool denyOverridesPredecessor(
+    const ExtendedEffect &first,
+    const ExtendedEffect &second)
+{
+    if (first.getEffect() == second.getEffect())
+        return first.getRuleId() < second.getRuleId();
+    return first.getEffect() < second.getEffect();
+}
+
+bool permitOverridePredecessor(
+    const ExtendedEffect &first,
+    const ExtendedEffect &second)
+{
+    if (first.getEffect() == second.getEffect())
+        return first.getRuleId() < second.getRuleId();
+    return first.getEffect() > second.getEffect();
+}
+
+} //anonymous namespace
+
+ExtendedEffect CombinerImpl::denyOverrides(const ExtendedEffectList &effects)
+{
+    if (isError(effects)) {
+        return Error;
+    }
+
+    ExtendedEffect result(Inapplicable);
+
+    FOREACH(it, effects) {
+        if (denyOverridesPredecessor(*it, result)) {
+            result = *it;
+        }
+    }
+    return result;
+}
+
+ExtendedEffect CombinerImpl::permitOverrides(const ExtendedEffectList &effects)
+{
+    if (isError(effects)) {
+        return Error;
+    }
+
+    // This magic number must be bigger that the bigest ruleId number from policy file.
+    ExtendedEffect result(Deny, 999999);
+
+    //Flag used to indicate that any of Deny,prompt-*,permit options appear
+    //Consequently if flag is true then result should be return, otherwise inapplicable should be returned
+    bool flag = false;
+    bool flagUndetermined = false;
+
+    FOREACH(it,effects) {
+        ExtendedEffect effect = *it;
+
+        if (effect.getEffect() == Permit) {
+            return effect;
+        } // no need for further check if "permit" found
+        if (effect.getEffect() == Undetermined) {
+            flagUndetermined = true;
+        } //check for undetermined
+
+        //Set the flag and the result even if effect is equal to result
+        //It is done to mark if any "Deny" effect occured
+        if (permitOverridePredecessor(effect, result)
+            && effect.getEffect() != Inapplicable
+            && effect.getEffect() != Undetermined)
+        {
+            result = effect;
+            flag = true;
+        }
+    }
+
+    if (flagUndetermined) {
+        return ExtendedEffect(Undetermined);
+    }
+
+    if (!flag) {
+        return ExtendedEffect(Inapplicable);
+    }
+    return result;
+}
+
+ExtendedEffect CombinerImpl::firstApplicable(
+    const ExtendedEffectList & effects)
+{
+  if (isError(effects)) {
+      return Error;
+  }
+
+  FOREACH(it,effects) {
+      if (it->getEffect() != Inapplicable) {
+          return *it;
+      }
+  }
+  return Inapplicable;
+}
+
+ExtendedEffect CombinerImpl::firstMatchingTarget(
+    const ExtendedEffectList &effects)
+{
+    if (isError(effects)) {
+        return Error;
+    }
+    // effect list constains result of policies which target has been matched.
+    //
+    // If target does not match policy result is NotMatchingTarget
+    // NotMatchingTarget values are not stored on the effects list
+    // (you can check it in combinePolicies function).
+    //
+    // So we are intrested in first value on the list.
+    return effects.empty() ? Inapplicable : effects.front();
+}
+
+bool CombinerImpl::isError(const ExtendedEffectList &effects)
+{
+    FOREACH(it, effects)
+    {
+        if (Error == it->getEffect()) {
+            return true;
+        }
+    }
+    return false;
+}
+
+ExtendedEffect CombinerImpl::combineRules(const TreeNode * policy)
+{
+    const Policy * policyObj = dynamic_cast<const Policy *>(policy->getElement());
+    if (!policyObj) {
+        LogError("dynamic_cast failed. PolicyObj is null.");
+        return Error;
+    }
+
+    Policy::CombineAlgorithm algorithm = policyObj->getCombineAlgorithm();
+
+    Assert(
+        algorithm != Policy::FirstTargetMatching &&
+        "Policy cannot have algorithm first target matching");
+
+    bool isUndetermined = false;
+
+    if (!checkIfTargetMatches(policyObj->getSubjects(), isUndetermined)) {
+        if (isUndetermined) {
+            //TODO Target is undetermined what should we do now ??
+            //Right now simply return NotMatchingTarget
+        }
+        //Target doesn't match
+        return NotMatchingTarget;
+    }
+    //Get all rules
+    const ChildrenSet & children = policy->getChildrenSet();
+    ChildrenConstIterator it = children.begin();
+    ExtendedEffectList effects;
+
+    while (it != children.end()) {
+        const Rule * rule = dynamic_cast<const Rule *>((*it)->getElement());
+
+        if (!rule) {
+            LogError("Error in dynamic_cast. rule is null");
+            return ExtendedEffect(Error);
+        }
+
+        ExtendedEffect effect = rule->evaluateRule(this->getAttributeSet());
+        effects.push_back(effect);
+        if (algorithm == Policy::FirstApplicable && effect.getEffect() != Inapplicable) {
+            //For first applicable algorithm we may stop after evaluating first policy
+            //which has effect other than inapplicable
+            break;
+        }
+        ++it;
+    } //end policy children iteration
+
+    //Use combining algorithm
+    ExtendedEffect ef = combine(policyObj->getCombineAlgorithm(), effects);
+    return ef;
+}
+
+//WARNING this method makes an assumption that Policy target is a policy child
+ExtendedEffect CombinerImpl::combinePolicies(const TreeNode * policy)
+{
+    const Policy * policySet = dynamic_cast<const Policy *>(policy->getElement());
+
+    if (!policySet) {
+        LogError("dynamic_cast failed. Policy set is null.");
+        return Error;
+    }
+
+    bool isUndetermined = false;
+    Policy::CombineAlgorithm algorithm = policySet->getCombineAlgorithm();
+
+    if (!checkIfTargetMatches(policySet->getSubjects(), isUndetermined)) {
+        /*   I can't explain this...
+        if (isUndetermined) {
+            if (algorithm == Policy::FirstTargetMatching) {
+                return Undetermined;
+            }
+        }
+        */
+        //Target doesn't match
+        return NotMatchingTarget;
+    }
+
+    const ChildrenSet & children = policy->getChildrenSet();
+
+    ExtendedEffectList effects;
+
+    FOREACH(it, children) {
+        ExtendedEffect effect;
+
+        if ((*it)->getTypeID() == TreeNode::PolicySet) {
+            effect = combinePolicies(*it);
+            if (effect.getEffect() != NotMatchingTarget) {
+                effects.push_back(effect);
+            }
+        } else if ((*it)->getTypeID() == TreeNode::Policy) {
+            effect = combineRules(*it);
+            if (effect.getEffect() != NotMatchingTarget) {
+                effects.push_back(effect);
+            }
+        } else {
+            // [CR] fix it
+            LogError("effect value is not initialized!");
+            return ExtendedEffect(Error);
+        }
+
+        if (algorithm == Policy::FirstTargetMatching
+            && effect.getEffect() != NotMatchingTarget)
+        {
+            //In First matching target algorithm we may return when first result is found
+            break;
+        }
+    }
+
+    //Use combining algorithm
+    return combine(policySet->getCombineAlgorithm(), effects);
+}
+
+ExtendedEffect CombinerImpl::combine(
+    Policy::CombineAlgorithm algorithm,
+    ExtendedEffectList &effects)
+{
+#ifdef ALL_LOGS
+    LogDebug("Effects to be combined with algorithm: " << ::toString(algorithm));
+    showEffectList(effects);
+#endif
+    switch (algorithm) {
+    case Policy::DenyOverride:
+        return denyOverrides(effects);
+        break;
+    case Policy::PermitOverride:
+        return permitOverrides(effects);
+        break;
+    case Policy::FirstApplicable:
+        return firstApplicable(effects);
+        break;
+    case Policy::FirstTargetMatching:
+        return firstMatchingTarget(effects);
+        break;
+    default:
+        Assert(false && "Wrong combining algorithm used");
+        return Error;
+    }
+}
+
+/**
+ *
+ * @param attrSet set of Subject attributes in policy that identifies target
+ * @return true if target  is determined and matches, false and isUndertmined is set to true if the target is undetermined
+ * false and isUndetermined set to false if target is determined but doesn't match
+ */
+bool CombinerImpl::checkIfTargetMatches(
+        const std::list<const Subject *> * subjectsList,
+        bool &isUndetermined)
+{
+    if (subjectsList->empty()) {
+        return true;
+    }
+
+    std::list<const Subject *>::const_iterator it = subjectsList->begin();
+    bool match = false;
+    //According to BONDI 1.0 at least one target must match
+    while (it != subjectsList->end()) {
+        match = (*it)->matchSubject(this->getAttributeSet(), isUndetermined);
+        if (match) { //at least one match
+            break;
+        }
+        ++it;
+    }
+
+    #ifdef _DEBUG
+    if (match == Attribute::MRTrue) {
+        LogDebug("Target matches ");
+    } else if (match == Attribute::MRUndetermined) {
+        LogDebug("Target match undetermined ");
+    } else {
+        LogDebug("Target doesn't match");
+    }
+    #endif
+    return match;
+}
+
diff --git a/ace/engine/Condition.cpp b/ace/engine/Condition.cpp
new file mode 100644 (file)
index 0000000..e92e681
--- /dev/null
@@ -0,0 +1,238 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+// File: Condition.cpp
+// Author: notroot
+//
+// Created on June 3, 2009, 9:00 AM
+//
+
+#include <iostream>
+#include <dpl/log/log.h>
+#include <dpl/foreach.h>
+#include <ace/Condition.h>
+
+/**
+ * Check if attribute in condition matches the values obtained from PIP
+ * attrSet - attributes from PIP
+ */
+
+Attribute::MatchResult Condition::evaluateCondition(
+        const AttributeSet * attrSet) const
+{
+    //Condition may include either matches of attributes or other conditions
+    //in this method all attributes are matched at first and if possible the
+    //condition is evaluated. If evaluation is not possible based solely on
+    //attributes then we start recursion into child conditions.
+
+    Attribute::MatchResult match;
+    bool undeterminedMatchFound = false;
+    bool isFinalMatch = false;
+
+#ifdef ALL_LOGS
+    LogDebug("Attributes to be matched");
+    printAttributes(*attrSet);
+    LogDebug("Condition attributes values");
+    printAttributes(attributes);
+#endif
+
+    if (this->isEmpty()) {
+        LogDebug("Condition is empty, returning true");
+        //Condition is empty, it means it evaluates to TRUE
+        return Attribute::MatchResult::MRTrue;
+    }
+
+    match = evaluateAttributes(attrSet, isFinalMatch, undeterminedMatchFound);
+    if (isFinalMatch) {
+        LogDebug("Evaluate attributes returning verdict" ) ; //<< match);
+        return match;
+    }
+
+    match = evaluateChildConditions(attrSet,
+                                    isFinalMatch,
+                                    undeterminedMatchFound);
+    if (isFinalMatch) {
+        LogDebug("Evaluate child conditions returning verdict" ); // << match);
+        return match;
+    }
+
+    if (undeterminedMatchFound) {
+        //If any  child condition/attribute-match was undetermined and
+        //so far we couldn't make a decision then we must return undetermined
+        LogDebug("Evaluate condition returning MRUndetermined");
+        return Attribute::MatchResult::MRUndetermined;
+    }
+
+    if (this->isAndCondition()) {
+        match = Attribute::MatchResult::MRTrue;
+    } else if (this->isOrCondition()) {
+        match = Attribute::MatchResult::MRFalse;
+    } else {
+        Assert(false && "Condition has to be either AND or OR");
+    }
+    return match;
+}
+
+// KW Attribute::MatchResult Condition::performORalgorithm(const std::set<Attribute>* attrSet) const{
+// KW
+// KW     Attribute::MatchResult match;
+// KW     bool undeterminedMatchFound = false;
+// KW     bool isFinalMatch = false;
+// KW
+// KW     LogDebug("Performing OR algorithm");
+// KW
+// KW     match = evaluateAttributes(attrSet, isFinalMatch, undeterminedMatchFound);
+// KW     if(isFinalMatch){
+// KW         LogDebug("OR algorithm evaluate attributes returning verdict" << match);
+// KW         return match;
+// KW     }
+// KW
+// KW     match = evaluateChildConditions(attrSet, isFinalMatch, undeterminedMatchFound);
+// KW     if(isFinalMatch){
+// KW         return match;
+// KW     }
+// KW
+// KW     if(undeterminedMatchFound){
+// KW         //If any  child condition/attribute-match was undetermined and
+// KW         //so far we couldn't make a decision then we must return undetermined
+// KW         LogDebug("OR algorithm returning MRUndetermined");
+// KW         return Attribute::MRUndetermined;
+// KW     }
+// KW
+// KW     LogDebug("OR algorithm returning MRFalse");
+// KW     return Attribute::MRFalse;
+// KW }
+
+// KW Attribute::MatchResult Condition::performANDalgorithm(const std::set<Attribute>* attrSet) const{
+// KW
+// KW
+// KW     Attribute::MatchResult match;
+// KW     bool undeterminedMatchFound = false;
+// KW     bool isFinalMatch = false;
+// KW
+// KW     LogDebug("Performing AND algorithm");
+// KW     match = evaluateAttributes(attrSet, isFinalMatch, undeterminedMatchFound);
+// KW     if(isFinalMatch){
+// KW         LogDebug("AND algorithm evaluate attributes returning verdict" << match);
+// KW         return match;
+// KW     }
+// KW     match = evaluateChildConditions(attrSet, isFinalMatch, undeterminedMatchFound);
+// KW     if(isFinalMatch){
+// KW         LogDebug("AND algorithm evaluate child returning verdict " << match);
+// KW         return match;
+// KW     }
+// KW     if(undeterminedMatchFound){
+// KW         //If any child condition/attribute-match was undetermined and
+// KW         //so far we couldn't make a decision then we must return undetermined
+// KW         LogDebug("AND algorithm returning Undetermined");
+// KW         return Attribute::MRUndetermined;
+// KW     }
+// KW
+// KW     LogDebug("AND algorithm returning MRTrue");
+// KW     return Attribute::MRTrue;
+// KW
+// KW }
+
+Attribute::MatchResult Condition::evaluateAttributes(
+        const AttributeSet * attrSet,
+        bool& isFinalMatch,
+        bool & undeterminedMatchFound) const
+{
+    Attribute::MatchResult match = Attribute::MatchResult::MRUndetermined;
+
+    std::list<Attribute>::const_iterator condIt = this->attributes.begin();
+    while (condIt != this->attributes.end()) {
+        //Find the value of needed attribute, based on attribute name
+        AttributeSet::const_iterator attr =
+                std::find_if(attrSet->begin(),
+                             attrSet->end(),
+                             AceDB::BaseAttribute::UnaryPredicate(&(*condIt)));
+        if (attr == attrSet->end()) {
+            LogError("Couldn't find required attribute. This should not happen");
+            Assert(
+                false &&
+                "Couldn't find attribute required in condition. This should not happen"
+                "This means that some attributes has not been obtained from PIP");
+            //Return undetermined here because it seems one of the attributes is unknown/undetermined
+            isFinalMatch = true;
+            match = Attribute::MatchResult::MRUndetermined;
+            break;
+        }
+
+        match = condIt->matchAttributes(&(*(*attr)));
+        if ((match == Attribute::MatchResult::MRFalse) && isAndCondition()) {
+            //FALSE match found in AND condition
+            isFinalMatch = true;
+            break;
+        } else if ((match == Attribute::MatchResult::MRTrue) && isOrCondition()) {
+            //TRUE match found in OR condition
+            isFinalMatch = true;
+            break;
+        } else if (match == Attribute::MatchResult::MRUndetermined) {
+            //Just mark that there was undetermined value found
+            undeterminedMatchFound = true;
+        }
+        ++condIt;
+    }
+
+    return match;
+}
+
+Attribute::MatchResult Condition::evaluateChildConditions(
+        const AttributeSet * attrSet,
+        bool& isFinalMatch,
+        bool & undefinedMatchFound) const
+{
+    Attribute::MatchResult match = Attribute::MatchResult::MRUndetermined;
+
+    std::list<Condition>::const_iterator it = conditions.begin();
+    while (it != conditions.end()) {
+        match = it->evaluateCondition(attrSet);
+
+        if ((match == Attribute::MatchResult::MRFalse) && isAndCondition()) {
+            //FALSE match found in AND condition
+            LogDebug("Child conditions results MRFalse)");
+            isFinalMatch = true;
+            break;
+        } else if ((match == Attribute::MatchResult::MRTrue) && isOrCondition()) {
+            //TRUE match found in OR condition
+            LogDebug("Child conditions result MRTrue");
+            isFinalMatch = true;
+            break;
+        } else if (match == Attribute::MatchResult::MRUndetermined) {
+            undefinedMatchFound = true;
+        }
+        ++it;
+    }
+
+    return match;
+}
+
+void Condition::getAttributes(AttributeSet * attrSet)
+{
+    //Get attributes from current condition
+    FOREACH (it, attributes)
+    {
+        AceDB::BaseAttributePtr attr(new Attribute(it->getName(), it->getMatchFunction(), it->getType()));
+        attrSet->insert(attr);
+    }
+    //Get attributes from any child conditions
+    FOREACH (it, conditions)
+    {
+        it->getAttributes(attrSet);
+    }
+}
+
diff --git a/ace/engine/ConfigurationManager.cpp b/ace/engine/ConfigurationManager.cpp
new file mode 100644 (file)
index 0000000..b134e28
--- /dev/null
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#include <dpl/assert.h>
+#include <dpl/log/log.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <error.h>
+#include <malloc.h>
+#include <sys/stat.h>
+#include <ace/ConfigurationManager.h>
+#include <unistd.h>
+
+using namespace std;
+
+namespace {
+const string currentXMLSchema("bondixml.xsd");
+}
+
+ConfigurationManager * ConfigurationManager::instance = NULL;
+
+
+string ConfigurationManager::getCurrentPolicyFile(void) const
+{
+    LogError("ConfigurationManager::getCurrentPolicyFile is DEPRECATED");
+    return "";
+}
+
+string ConfigurationManager::getFullPathToCurrentPolicyFile(void) const
+{
+    LogError("ConfigurationManager::getFullPathToCurrentPolicyFile"
+             "is DEPRECATED");
+    return "";
+}
+
+string ConfigurationManager::getFullPathToCurrentPolicyXMLSchema(void) const
+{
+    LogError("ConfigurationManager::getFullPathToCurrentPolicyXMLSchema"
+             "is DEPRECATED");
+    return "";
+}
+
+int ConfigurationManager::addPolicyFile(const string &)
+{
+    LogError("ConfigurationManager::addPolicyFile is DEPRECATED");
+    return CM_GENERAL_ERROR;
+}
+
+int ConfigurationManager::removePolicyFile(const string&)
+{
+    LogError("ConfigurationManager::removePolicyFile is DEPRECATED");
+    return CM_GENERAL_ERROR;
+}
+
+int ConfigurationManager::changeCurrentPolicyFile(const string&)
+{
+    LogError("ConfigurationManager::changeCurrentPolicyFile is DEPRECATED");
+    return CM_GENERAL_ERROR;
+}
+
+string ConfigurationManager::extractFilename(const string&) const
+{
+    LogError("ConfigurationManager::extractFilename is DEPRECATED");
+    return "";
+}
+
+
+int ConfigurationManager::parse(const string&)
+{
+    LogError("ConfigurationManager::parse is DEPRECATED");
+    return CM_GENERAL_ERROR;
+}
+
+bool ConfigurationManager::copyFile(FILE*, FILE*, int) const
+{
+    LogError("ConfigurationManager::copyFile is DEPRECATED");
+    return false;
+}
+
+bool ConfigurationManager::checkIfFileExistst(const string&) const
+{
+    LogError("ConfigurationManager::checkIfFileExistst is DEPRECATED");
+    return false;
+}
+
+const list<string> & ConfigurationManager::getPolicyFiles() const
+{
+    LogError("ConfigurationManager::getPolicyFiles is DEPRECATED");
+    static list<string> aList;
+    return aList;
+}
+
+const string & ConfigurationManager::getConfigFile() const
+{
+    LogError("ConfigurationManager::getConfigFile is DEPRECATED");
+    static string returnString("");
+    return returnString;
+}
+
+string ConfigurationManager::getFullPathToPolicyFile(PolicyType policy) const
+{
+    string cscStoragePath = getCscStoragePath();
+    string storagePath = getStoragePath();
+    string fileName;
+
+    switch (policy) {
+    case PolicyType::WAC2_0: {
+        fileName = ACE_WAC_POLICY_FILE_NAME;
+        break; }
+    case PolicyType::Tizen: {
+        fileName = ACE_TIZEN_POLICY_FILE_NAME;
+        break; }
+    default: {
+        LogError("Invalid policy file requested");
+        return ""; }
+    }
+    string cscPolicyFilePath = cscStoragePath + fileName;
+    if ( access(cscPolicyFilePath.c_str(), R_OK) == -1)
+        return storagePath + fileName;
+
+    return cscPolicyFilePath;
+}
+
+string ConfigurationManager::getFullPathToPolicyXMLSchema() const
+{
+    string storagePath = getStoragePath();
+    if (*(storagePath.rbegin()) == '/')
+    {
+        return storagePath + currentXMLSchema;
+    }
+    return storagePath + "/" + currentXMLSchema;
+}
+
+string ConfigurationManager::getStoragePath(void) const
+{
+    return ACE_MAIN_STORAGE;
+}
+
+string ConfigurationManager::getCscStoragePath(void) const
+{
+    return ACE_CSC_STORAGE;
+}
diff --git a/ace/engine/Policy.cpp b/ace/engine/Policy.cpp
new file mode 100644 (file)
index 0000000..7443090
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Policy.cpp
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#include <ace/Policy.h>
+
+Policy::~Policy()
+{
+    for (std::list<const Subject *>::iterator it = subjects->begin();
+         it != subjects->end();
+         ++it) {
+        delete *it;
+    }
+    delete subjects;
+}
+
+void Policy::printData()
+{
+    std::string subject;
+    if (subjects != NULL && subjects->size()) {
+        subject = (subjects->front())->getSubjectId();
+    }
+    std::string algorithm = printCombineAlgorithm(this->combineAlgorithm);
+
+    std::cout << "subject: " << subject << " algorithm: " << algorithm <<
+    std::endl;
+}
+
+std::string Policy::printCombineAlgorithm(CombineAlgorithm algorithm)
+{
+    switch (algorithm) {
+    case DenyOverride:
+        return "DenyOverride";
+    case PermitOverride:
+        return "PermitOverride";
+    case FirstApplicable:
+        return "FirstApplicable";
+    case FirstTargetMatching:
+        return "FirstTargetMatching";
+    default:
+        return "ERROR: Wrong Algorithm";
+    }
+}
+
+const char * toString(Policy::CombineAlgorithm algorithm)
+{
+    switch (algorithm) {
+    case Policy::DenyOverride:
+        return "DenyOverride";
+    case Policy::PermitOverride:
+        return "PermitOverride";
+    case Policy::FirstApplicable:
+        return "FirstApplicable";
+    case Policy::FirstTargetMatching:
+        return "FirstTargetMatching";
+    default:
+        return "ERROR: Wrong Algorithm";
+    }
+}
diff --git a/ace/engine/PolicyEnforcementPoint.cpp b/ace/engine/PolicyEnforcementPoint.cpp
new file mode 100644 (file)
index 0000000..1db8488
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file    security_logic.cpp
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @version 1.0
+ * @brief   Implementation file for security logic
+ */
+#include <ace/PolicyEnforcementPoint.h>
+
+#include <sstream>
+#include <algorithm>
+#include <list>
+#include <string>
+#include <sstream>
+#include <stdexcept>
+#include <cstdlib>
+#include <map>
+
+#include <dpl/assert.h>
+#include <dpl/exception.h>
+#include <dpl/log/log.h>
+
+#include <ace/PolicyEvaluatorFactory.h>
+#include <ace/PolicyResult.h>
+#include <ace/Request.h>
+
+PolicyEnforcementPoint::PolicyEnforcementPoint() :
+    m_wrt(0),
+    m_res(0),
+    m_sys(0),
+    m_pdp(0),
+    m_pip(0)
+{}
+
+void PolicyEnforcementPoint::terminate()
+{
+    LogInfo("PolicyEnforcementPoint is being deinitialized.");
+
+    delete m_sys;
+    delete m_res;
+    delete m_wrt;
+    delete m_pdp;
+    delete m_pip;
+    m_sys = 0;
+    m_res = 0;
+    m_wrt = 0;
+    m_pdp = 0;
+    m_pip = 0;
+}
+
+PolicyEnforcementPoint::~PolicyEnforcementPoint()
+{
+    Assert((m_sys == 0) && "You must run "
+           "PolicyEnforcementPoint::Deinitialize before exit program!");
+}
+
+void PolicyEnforcementPoint::initialize(
+        IWebRuntime *wrt,
+        IResourceInformation *resource,
+        IOperationSystem *operation)
+{
+    if (m_wrt) {
+        ThrowMsg(PEPException::AlreadyInitialized,
+                 "Policy Enforcement Point is already initialzed");
+    }
+
+    m_wrt = wrt;
+    m_res = resource;
+    m_sys = operation;
+
+    if (this->m_pip != NULL) {
+        this->m_pip->update(m_wrt, m_res, m_sys);
+        return;
+    }
+
+    this->m_pip = new PolicyInformationPoint(wrt, m_res, m_sys);
+    this->m_pdp = new PolicyEvaluator(m_pip);
+
+    if (!this->m_pdp->initPDP()) {
+        Assert(0);
+    }
+}
+
+ExtendedPolicyResult PolicyEnforcementPoint::check(Request &request)
+{
+    return m_pdp->getPolicyForRequest(request);
+}
+
+void PolicyEnforcementPoint::updatePolicy(const std::string &policy)
+{
+    LogDebug("ACE updatePolicy: " << policy);
+    int errorCode = 0;
+
+    if (m_pdp == NULL) {
+        LogError("Evaluator not set. Ignoring message.");
+        Assert(false && "UpdateClient error on receiving event");
+    } else {
+        LogDebug("Emitting update signal.");
+        errorCode = m_pdp->updatePolicy(policy.c_str());
+    }
+
+    LogDebug("Sending reponse: " << errorCode);
+}
+
+void PolicyEnforcementPoint::updatePolicy()
+{
+    LogDebug("ACE updatePolicy");
+    if (m_pdp == NULL) {
+        LogError("Evaluator not set. Ignoring message.");
+    } else {
+        m_pdp->updatePolicy();
+    }
+}
+
+OptionalExtendedPolicyResult PolicyEnforcementPoint::checkFromCache(Request &request)
+{
+   return m_pdp->getPolicyForRequestFromCache(request);
+}
+
+OptionalExtendedPolicyResult PolicyEnforcementPoint::check(Request &request,
+                                                   bool fromCacheOnly)
+{
+   return m_pdp->getPolicyForRequest(request, fromCacheOnly);
+}
diff --git a/ace/engine/PolicyEvaluator.cpp b/ace/engine/PolicyEvaluator.cpp
new file mode 100644 (file)
index 0000000..342f257
--- /dev/null
@@ -0,0 +1,544 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PolicyEvaluator.cpp
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+
+#include <ace/Attribute.h>
+#include <ace/PolicyEvaluator.h>
+#include <ace/TreeNode.h>
+#include <ace/Policy.h>
+#include <ace/Rule.h>
+#include <ace/Attribute.h>
+#include <ace/SettingsLogic.h>
+#include <ace-dao-rw/AceDAO.h>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace/parser.h>
+
+using namespace AceDB;
+
+PolicyEvaluator::~PolicyEvaluator()
+{
+    delete m_combiner;
+}
+
+PolicyEvaluator::PolicyEvaluator(PolicyInformationPoint * pip) :
+    m_uniform_policy(NULL),
+    m_wac_policy(NULL),
+    m_tizen_policy(NULL),
+    m_policy_to_use(PolicyType::WAC2_0),
+    m_combiner(new CombinerImpl()),
+    m_verdictListener(NULL),
+    m_pip(pip)
+{}
+
+bool PolicyEvaluator::initPDP()
+{
+    updatePolicy();
+    // TODO change return value someday to void?
+    return true;
+}
+
+bool PolicyEvaluator::fillAttributeWithPolicy()
+{
+    if (m_attributeSet.empty()) {
+        if (!extractAttributes(m_uniform_policy)) {
+            LogInfo("Warning attribute set cannot be extracted. "
+                    "Returning Deny");
+            return false;
+        }
+        // Adding widget type attribute to distinguish WAC/Tizen widgets
+        /**
+         * This special attribute of WidgetParam type is handled
+         * in PolicyInformationPoint, it is based on WidgetType
+         * fron WRT database.
+         *
+         * It is needed to distinguish cached policy results and cached prompt
+         * responses for different policies (WAC/Tizen/any possible
+         * other in the future).
+         */
+        AceDB::BaseAttributePtr attribute(new AceDB::BaseAttribute());
+        attribute->setName(POLICY_WIDGET_TYPE_ATTRIBUTE_NAME);
+        attribute->setType(AceDB::BaseAttribute::Type::WidgetParam);
+        m_attributeSet.insert(attribute);
+        AceDAO::addAttributes(m_attributeSet);
+    } else {
+        LogDebug("Required attribute set already loaded");
+    }
+    return true;
+}
+
+PolicyResult PolicyEvaluator::effectToPolicyResult(Effect effect)
+{
+    if (Effect::Deny == effect) {
+        return PolicyEffect::DENY;
+    }
+    if (Effect::Undetermined == effect) {
+        return PolicyResult::Value::UNDETERMINED;
+    }
+    if (Effect::PromptOneShot == effect) {
+        return PolicyEffect::PROMPT_ONESHOT;
+    }
+    if (Effect::PromptSession == effect) {
+        return PolicyEffect::PROMPT_SESSION;
+    }
+    if (Effect::PromptBlanket == effect) {
+        return PolicyEffect::PROMPT_BLANKET;
+    }
+    if (Effect::Permit == effect) {
+        return PolicyEffect::PERMIT;
+    }
+    if (Effect::Inapplicable == effect) {
+        return PolicyDecision::Value::NOT_APPLICABLE;
+    }
+    return PolicyEffect::DENY;
+}
+
+OptionalExtendedPolicyResult PolicyEvaluator::getPolicyForRequestInternal(
+        bool fromCacheOnly)
+{
+    //ADD_PROFILING_POINT("Search cached verdict in database", "start");
+
+    OptionalExtendedPolicyResult result = AceDAO::getPolicyResult(m_attributeSet);
+
+    //ADD_PROFILING_POINT("Search cached verdict in database", "stop");
+
+    if (fromCacheOnly || !!result) {
+        return result;
+    }
+
+    //ADD_PROFILING_POINT("EvaluatePolicy", "start");
+
+    ExtendedEffect policyEffect = evaluatePolicies(getCurrentPolicyTree());
+
+    //ADD_PROFILING_POINT("EvaluatePolicy", "stop");
+
+    LogDebug("Policy effect is: " << toString(policyEffect.getEffect()));
+
+    ExtendedPolicyResult exResult(
+        effectToPolicyResult(policyEffect.getEffect()),
+        policyEffect.getRuleId());
+
+    AceDAO::setPolicyResult(this->m_attributeSet, exResult);
+    return OptionalExtendedPolicyResult(exResult);
+}
+
+// +----------------+---------+---------+------+--------+
+// |\User setting   | PERMIT  | PROMPT* | DENY | DEF    |
+// |      \         |         |         |      |        |
+// |Policy result\  |         |         |      |        |
+// |----------------+---------+---------+------+--------+
+// |PERMIT          | PERMIT  | PROMPT* | DENY | PERMIT |
+// |----------------+---------+---------+------+--------+
+// |PROMPT*         | PROMPT* | PR MIN  | DENY | PROMPT*|
+// |----------------+---------+---------+------+--------+
+// |DENY            | DENY    | DENY    | DENY | DENY   |
+// |----------------+---------+---------+------+--------+
+// |UNDETERMIND     | UNDET   | UNDET   | DENY | UNDET  |
+// |----------------+---------+---------+------+--------+
+// |NOT_AP          | PEMIT   | PROMPT* | DENY | NOT_AP |
+// +----------------+---------+---------+------+--------+
+
+static PolicyResult getMostRestrict(
+        PreferenceTypes globalPreference,
+        const PolicyResult &policyResult)
+{
+    if (globalPreference == PreferenceTypes::PREFERENCE_PERMIT
+            && policyResult == PolicyEffect::PERMIT) {
+        return PolicyEffect::PERMIT;
+    }
+
+    if (globalPreference == PreferenceTypes::PREFERENCE_DENY
+            || policyResult == PolicyEffect::DENY) {
+        return PolicyEffect::DENY;
+    }
+
+    if (policyResult == PolicyResult::UNDETERMINED) {
+        return PolicyResult::UNDETERMINED;
+    }
+
+    if (globalPreference == PreferenceTypes::PREFERENCE_DEFAULT) {
+        return policyResult;
+    }
+
+    if (globalPreference == PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT
+            || policyResult == PolicyEffect::PROMPT_ONESHOT) {
+        return PolicyEffect::PROMPT_ONESHOT;
+    }
+
+    if (globalPreference == PreferenceTypes::PREFERENCE_SESSION_PROMPT
+            || policyResult == PolicyEffect::PROMPT_SESSION) {
+        return PolicyEffect::PROMPT_SESSION;
+    }
+
+    if (globalPreference == PreferenceTypes::PREFERENCE_BLANKET_PROMPT
+            || policyResult == PolicyEffect::PROMPT_BLANKET) {
+        return PolicyEffect::PROMPT_BLANKET;
+    }
+
+    return PolicyEffect::PERMIT;
+}
+
+OptionalExtendedPolicyResult PolicyEvaluator::getPolicyForRequestFromCache(
+        const Request &request)
+{
+    return getPolicyForRequest(request, true);
+}
+
+ExtendedPolicyResult PolicyEvaluator::getPolicyForRequest(const Request &request)
+{
+    auto result = this->getPolicyForRequest(request, false);
+    Assert(!!result
+                    && "Policy always has to be evaluated to valid state");
+    return *result;
+}
+
+OptionalExtendedPolicyResult PolicyEvaluator::getPolicyForRequest(
+        const Request &request,
+        bool fromCacheOnly)
+{
+    //ADD_PROFILING_POINT("getPolicyForRequest", "start");
+    m_attributeSet.clear();
+
+    switch (request.getAppType()) {
+        case Request::APP_TYPE_TIZEN:
+            m_policy_to_use = PolicyType::Tizen;
+            LogDebug("==== Using Tizen policy ====");
+            break;
+        case Request::APP_TYPE_WAC20:
+            m_policy_to_use = PolicyType::WAC2_0;
+            LogDebug("==== Using WAC policy ====");
+            break;
+        default:
+            LogError("Unsupported(unknown) widget type. Access denied.");
+            return OptionalExtendedPolicyResult(
+                ExtendedPolicyResult(PolicyEffect::DENY));
+    }
+
+    try {
+        // Check which attributes should be used
+        // memory alocated, free in destructor
+        //ADD_PROFILING_POINT("getAttributes", "start");
+        AceDB::AceDAO::getAttributes(&m_attributeSet);
+        //ADD_PROFILING_POINT("getAttributes", "stop");
+
+        // If attributes can't be resolved then check the policy
+        if (!fillAttributeWithPolicy()) {
+            //ADD_PROFILING_POINT("getPolicyForRequest", "stop");
+            return OptionalExtendedPolicyResult(
+                ExtendedPolicyResult(PolicyEffect::DENY));
+        }
+
+        //ADD_PROFILING_POINT("getAttributesValues", "start");
+        m_pip->getAttributesValues(&request, &m_attributeSet);
+        //ADD_PROFILING_POINT("getAttributesValues", "stop");
+        LogDebug("==== Attributes set by PIP ====");
+        printAttributes(m_attributeSet);
+        LogDebug("==== End of attributes set by PIP ====");
+
+        OptionalExtendedPolicyResult policyResult = getPolicyForRequestInternal(
+                fromCacheOnly);
+
+        if (!policyResult) {
+            if (!fromCacheOnly) {
+                LogError("Policy evaluated to NULL value");
+                Assert(false && "Policy evaluated to NULL value");
+            }
+            return OptionalExtendedPolicyResult();
+        }
+        LogDebug("==== getPolicyForRequestInternal result (PolicyResult): "
+                 << policyResult->policyResult << "=====");
+
+        PreferenceTypes globalPreference =
+                SettingsLogic::findGlobalUserSettings(request);
+
+        auto ret = getMostRestrict(globalPreference, policyResult->policyResult);
+        //ADD_PROFILING_POINT("getPolicyForRequest", "stop");
+        return OptionalExtendedPolicyResult(
+            ExtendedPolicyResult(ret, policyResult->ruleId));
+
+    } catch (AceDB::AceDAO::Exception::DatabaseError &e) {
+        LogError("Database error");
+        DPL::Exception::DisplayKnownException(e);
+        //ADD_PROFILING_POINT("getPolicyForRequest", "stop");
+        return OptionalExtendedPolicyResult(
+            ExtendedPolicyResult(PolicyEffect::DENY));
+    }
+}
+
+bool PolicyEvaluator::extractAttributes(TreeNode* policyTree)
+{
+    if (NULL == policyTree) {
+        return false;
+    }
+
+    //We check if root target matches. In general the root's target should
+    //be empty. Otherwise it would have to have all the subjects available
+    //specified but just to be on the safe side (and for tests) this checking
+    const Policy * policy =
+            dynamic_cast<const Policy *>(policyTree->getElement());
+    Assert(policy != NULL
+                  && "Policy element has been null while attribute extracting");
+
+    extractTargetAttributes(policy);
+    extractAttributesFromSubtree(policyTree); //Enter recursion
+
+    return true;
+}
+
+void PolicyEvaluator::extractTargetAttributes(const Policy *policy)
+{
+    std::list<const Subject *>::const_iterator it =
+            policy->getSubjects()->begin();
+    for (; it != policy->getSubjects()->end(); ++it) {
+        const std::list<Attribute> & attrList = (*it)->getTargetAttributes();
+        FOREACH(it2, attrList)
+        {
+            BaseAttributePtr attr(
+                    new Attribute((*it2).getName(), (*it2).getMatchFunction(),
+                            (*it2).getType()));
+            m_attributeSet.insert(attr);
+        }
+    }
+}
+
+TreeNode * PolicyEvaluator::getCurrentPolicyTree()
+{
+    TreeNode * currentPolicy = NULL;
+    switch (m_policy_to_use) {
+    case PolicyType::Tizen: {
+        currentPolicy = m_tizen_policy;
+        break;}
+    case PolicyType::WAC2_0: {
+        currentPolicy = m_wac_policy;
+        break;}
+    default: {
+        LogError("Invalid policy type to use");}
+    }
+    return currentPolicy;
+}
+
+/**
+ *
+ * @param *root - the root of the original (full) subtree of politics
+ * @param *newRoot - the pointer to the root of the copy (reduced) subtree of politics
+ */
+void PolicyEvaluator::extractAttributesFromSubtree(const TreeNode *root)
+{
+    const ChildrenSet & children = root->getChildrenSet();
+
+    for (std::list<TreeNode *>::const_iterator it = children.begin();
+            it != children.end(); ++it) {
+        TreeNode * node = *it;
+        if (node->getTypeID() != TreeNode::Policy
+                && node->getTypeID() != TreeNode::PolicySet) {
+            //It is not a policy so we may be sure that we have already
+            //checked that SubjectId matches
+            //Add new node to new tree and extract attributes
+
+            extractAttributesFromRules(node);
+        } else { //TreeNode is a Policy or PolicySet
+            const Policy * policy =
+                    dynamic_cast<const Policy *>(node->getElement());
+                    //We will be needing also the attributes from target
+            if (policy) {
+                extractTargetAttributes(policy);
+            } else {
+                LogError(" extractAttributesFromSubtree policy=NULL");
+            }
+            //Enter recursion
+            extractAttributesFromSubtree(node);
+        }
+    }
+}
+
+bool PolicyEvaluator::extractAttributesFromRules(const TreeNode *root)
+{
+    Assert(root->getTypeID() == TreeNode::Rule
+       && "Tree structure, extracting attributes from node that is not a rule");
+    Rule * rule = dynamic_cast<Rule *>(root->getElement());Assert
+    (rule != NULL);
+    //Get attributes from rule
+    rule->getAttributes(&m_attributeSet);
+
+    //[CR] consider returned value, because its added only to eliminate errors
+    return true;
+}
+
+ExtendedEffect PolicyEvaluator::evaluatePolicies(const TreeNode * root)
+{
+    if (root == NULL) {
+        LogInfo("Error: policy tree doesn't exist. "
+                "Probably xml file is missing");
+        return Deny;
+    }
+
+    if (m_attributeSet.empty()) {
+        LogInfo("Warning: evaluatePolicies: attribute set was empty");
+    }
+    m_combiner->setAttributeSet(&m_attributeSet);
+    return m_combiner->combinePolicies(root);
+}
+
+
+int PolicyEvaluator::updatePolicy(const char* newPolicy)
+{
+    LogError("PolicyEvaluator::updatePolicy is DEPRECATED");
+    ConfigurationManager* configMgr = ConfigurationManager::getInstance();
+    if (NULL == configMgr) {
+        LogError("ACE fatal error: failed to create configuration manager");
+        return POLICY_PARSING_ERROR;
+    }
+    int result = POLICY_PARSING_SUCCESS;
+    if (newPolicy == NULL) {
+        LogError("Policy Update: incorrect policy name");
+        return POLICY_FILE_ERROR;
+    }
+    LogDebug("Starting update policy: " << newPolicy);
+
+    Parser parser;
+    TreeNode *backup = m_uniform_policy;
+
+    m_uniform_policy = parser.parse(newPolicy,
+            configMgr->getFullPathToPolicyXMLSchema());
+
+    if (NULL == m_uniform_policy) {
+        m_uniform_policy = backup;
+        LogError("Policy Update: corrupted policy file");
+        result = POLICY_PARSING_ERROR;
+    } else {
+        m_currentPolicyFile = newPolicy;
+        m_wac_policy = m_uniform_policy;  //we must be able to use WAC widgets
+        m_tizen_policy = m_uniform_policy;//we must be able to use Tizen widgets
+        m_attributeSet.clear();
+        backup->releaseResources();
+        LogInfo("Policy Update: successful.");
+        try {
+            AceDAO::resetDatabase();   // TODO: this is strange, but this
+                                       // method is deprecated so not changing
+                                       // it (will disappear with entire method)
+        } catch (AceDAO::Exception::DatabaseError &e) {
+        }
+    }
+    return result;
+}
+
+TreeNode * PolicyEvaluator::getDefaultSafePolicyTree(void)
+{
+    Policy * policy = new Policy;
+    Rule * rule = new Rule;
+    TreeNode * mainTree = NULL,
+             * childTree = NULL;
+
+    policy->setCombineAlgorithm(Policy::CombineAlgorithm::DenyOverride);
+    rule->setEffect(Deny);
+
+    mainTree = new TreeNode(m_uniform_policy, TreeNode::Policy, policy);
+    childTree = new TreeNode(mainTree, TreeNode::Rule, rule);
+    mainTree->addChild(childTree);
+
+    LogError("Loading default safe policy tree");
+    return mainTree;
+}
+
+void PolicyEvaluator::updatePolicy()
+{
+    ConfigurationManager *configMgr = ConfigurationManager::getInstance();
+    Assert(NULL != configMgr && "ACE fatal error: failed to "
+           "create configuration manager");
+    AceDAO::clearPolicyCache();
+    if (NULL != m_uniform_policy) {
+        m_uniform_policy->releaseResources();
+    }
+    Parser parserWac, parserTizen;
+    m_wac_policy = parserWac.parse(
+            configMgr->getFullPathToPolicyFile(PolicyType::WAC2_0),
+            configMgr->getFullPathToPolicyXMLSchema());
+    if (NULL == m_wac_policy) {
+        LogError("ACE fatal error: cannot parse XML file (WAC policy)");
+        m_wac_policy = getDefaultSafePolicyTree();
+    }
+    m_tizen_policy = parserTizen.parse(
+            configMgr->getFullPathToPolicyFile(PolicyType::Tizen),
+            configMgr->getFullPathToPolicyXMLSchema());
+    if (NULL == m_tizen_policy) {
+        LogError("ACE fatal error: cannot parse XML file (Tizen policy)");
+        m_tizen_policy = getDefaultSafePolicyTree();
+    }
+    // Policy set is usefull for releasing all policies in case of
+    // policy change
+    Policy * policySet = new PolicySet();
+    policySet->setCombineAlgorithm(Policy::CombineAlgorithm::DenyOverride);
+    m_uniform_policy = new TreeNode(NULL, TreeNode::PolicySet, policySet);
+    m_uniform_policy->addChild(m_wac_policy);
+    m_uniform_policy->addChild(m_tizen_policy);
+
+    // Creating attribute set for the first time after loading policy
+    // to speed up queries
+    m_attributeSet.clear();
+    fillAttributeWithPolicy();
+}
+
+std::string PolicyEvaluator::getCurrentPolicy()
+{
+    LogError("PolicyEvaluator::getCurrentPolicy is DEPRECATED");
+    return m_currentPolicyFile;
+}
+
+const char * toString(Validity validity)
+{
+    switch (validity) {
+    case Validity::ONCE:
+        return "Once";
+        break;
+    case Validity::SESSION:
+        return "Session";
+    case Validity::ALWAYS:
+        return "Always";
+    default:
+        return "WRONG VALIDITY";
+    }
+}
+
+const char * toString(Verdict verdict)
+{
+    switch (verdict) {
+    case Verdict::VERDICT_PERMIT:
+        return "Permit";
+    case Verdict::VERDICT_DENY:
+        return "Deny";
+    case Verdict::VERDICT_INAPPLICABLE:
+        return "Inapplicable";
+    case Verdict::VERDICT_UNKNOWN:
+        return "Unknown";
+    case Verdict::VERDICT_UNDETERMINED:
+        return "Undetermined";
+    case Verdict::VERDICT_ERROR:
+        return "Error";
+    case Verdict::VERDICT_ASYNC:
+        return "Async";
+    default:
+        return "Wrong verdict value";
+    }
+}
diff --git a/ace/engine/PolicyInformationPoint.cpp b/ace/engine/PolicyInformationPoint.cpp
new file mode 100644 (file)
index 0000000..b273809
--- /dev/null
@@ -0,0 +1,278 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PolicyInformationPoint.cpp
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+#include <map>
+#include <string>
+#include <list>
+
+#include <ace/PolicyInformationPoint.h>
+#include <ace/ConfigurationManager.h>
+
+#include <dpl/log/log.h>
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+
+#include <ace/Attribute.h>
+#include <ace-dao-ro/BaseAttribute.h>
+#include <ace-dao-ro/AceDAOReadOnly.h>
+
+using namespace AceDB;
+
+PolicyInformationPoint::PolicyInformationPoint(IWebRuntime *wrt,
+        IResourceInformation *resource,
+        IOperationSystem *system) : wrtInterface(wrt),
+    resourceInformation(resource),
+    operationSystem(system)
+{
+    AceDB::AceDAOReadOnly::attachToThreadRO();
+}
+
+PolicyInformationPoint::~PolicyInformationPoint()
+{
+    AceDB::AceDAOReadOnly::detachFromThread();
+}
+
+/* gather attributes values from adequate interfaces */
+PipResponse PolicyInformationPoint::getAttributesValues(const Request* request,
+        AttributeSet* attributes)
+{
+    int subjectReturn = 0;
+    int resourceReturn = 0;
+    int operationReturn = 0;
+    int functionReturn = 0;
+    /* create query lists  */
+    createQueries(attributes);
+
+    /* check if subject attributes query has any elements*/
+    if (!subjectAttributesQuery.empty()) {
+        /* get Subject Attributes */
+        subjectReturn = wrtInterface->getAttributesValues(
+                *request,
+                &subjectAttributesQuery);
+    }
+
+    AttributeSet::const_iterator iter2;
+    FOREACH(iter, subjectAttributesQuery)
+    {
+        if (iter->second == NULL) {
+            Attribute attr(*(iter->first));
+            attr.setType(Attribute::Type::Subject);
+            iter2 = std::find_if(attributes->begin(),
+                                 attributes->end(),
+                                 BaseAttribute::UnaryPredicate(&attr));
+            Assert(iter2 != attributes->end() && "This should not happen, "
+                   "the attribute MUST be in attribute set");
+            (*iter2)->setUndetermind(true);
+        }
+    }
+
+    /* check if resource  attributes query has any elements*/
+    if (!resourceAttributesQuery.empty()) {
+        /* get Resource Attributes */
+        resourceReturn = resourceInformation->getAttributesValues(
+                *request,
+                &resourceAttributesQuery);
+        /* error analyzys*/
+        resourceReturn <<= ERROR_SHIFT_RESOURCE;
+    }
+
+    FOREACH(iter, resourceAttributesQuery)
+    {
+        if (iter->second == NULL) {
+            LogInfo("Found undetermined attribute");
+            Attribute attr(*(iter->first));
+            attr.setType(Attribute::Type::Resource);
+            iter2 = std::find_if(attributes->begin(),
+                                 attributes->end(),
+                                 BaseAttribute::UnaryPredicate(&attr));
+            Assert(iter2 != attributes->end() && "This should not happen, "
+                   "the attribute MUST be in attribute set");
+            (*iter2)->setUndetermind(true);
+        }
+    }
+
+    /* check if resource  attributes query has any elements*/
+    if (!environmentAttributesQuery.empty()) {
+        /* get enviroment attributes  */
+        operationReturn = operationSystem->getAttributesValues(
+                *request,
+                &environmentAttributesQuery);
+        /* error analyzys*/
+        operationReturn <<= ERROR_SHIFT_OS;
+    }
+
+    FOREACH(iter, environmentAttributesQuery)
+    {
+        if (iter->second == NULL) {
+            //it doesnt change uniqueness of a set element so we can const_cast
+            Attribute attr(*(iter->first));
+            attr.setType(Attribute::Type::Environment);
+            iter2 = find_if(attributes->begin(),
+                            attributes->end(),
+                            BaseAttribute::UnaryPredicate(&attr));
+            Assert(iter2 != attributes->end() && "This should not happen, "
+                   "the attribute MUST be in attribute set");
+            (*iter2)->setUndetermind(true);
+        }
+    }
+
+    /* check if functionParam attributes query has any elements*/
+    if (!functionParamAttributesQuery.empty() && request->getFunctionParam()) {
+        /* get params attributes  */
+        functionReturn = request->getFunctionParam()->getAttributesValues(
+                *request,
+                &functionParamAttributesQuery);
+        /* error analyzys*/
+        functionReturn <<= ERROR_SHIFT_FP;
+    }
+
+    FOREACH(iter, functionParamAttributesQuery)
+    {
+        if (iter->second == NULL) {
+            //it doesnt change uniqueness of a set element so we can const_cast
+            Attribute attr(*(iter->first));
+            attr.setType(Attribute::Type::FunctionParam);
+            iter2 = find_if(attributes->begin(),
+                            attributes->end(),
+                            BaseAttribute::UnaryPredicate(&attr));
+            Assert(iter2 != attributes->end() && "This should not happen, "
+                   "the attribute MUST be in attribute set");
+            (*iter2)->setUndetermind(true);
+        }
+    }
+
+    // Here we must add to attributes proper marking of policy type
+    // (Tizen or WAC widget)
+    /**
+     * This part of code seems odd here, but we don't want to keep it in
+     * attribute fascade, as it is maintained by ACE clients and we are not
+     * sure if this kind of distinction between different policies will be ok
+     * as final solution.
+     *
+     * This is somehow private part of ACE, so it may be moved into
+     * separate ACEAttributeFascade kind of a class in (already planned)
+     * refactoring, when moving to new, C-only API for ACE.
+     */
+    if (widgetParamAttributesQuery.empty()) {
+        LogError("No attrbutes of WidgetParam type present - "
+                 "should be widget type at least");
+    } else {
+        LogDebug("WidgetParam type atributes present, searching for widget type");
+        FOREACH(iter, widgetParamAttributesQuery) {
+            const std::string *name = iter->first;
+            if (POLICY_WIDGET_TYPE_ATTRIBUTE_NAME == *name) {
+                LogDebug("Widget type attribute found");
+
+                // Extracting widget type
+                std::list<std::string> attrValue;
+                Try {
+                    AceDB::AppTypes appType =
+                        AceDB::AceDAOReadOnly::getWidgetType(
+                            request->getWidgetHandle());
+                    switch (appType) {
+                    case AceDB::AppTypes::Tizen : {
+                        attrValue.push_back(POLICY_NAME_TIZEN);
+                        LogDebug("==== Using Tizen policy in PIP ====");
+                        break;}
+                    case AceDB::AppTypes::WAC20 : {
+                        attrValue.push_back(POLICY_NAME_WAC2_0);
+                        LogDebug("==== Using WAC policy in PIP ====");
+                        break;}
+                    default: {
+                        LogError("Invalid widget type");
+                        }
+                    }
+                } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError)
+                {
+                    LogError("Couldn't find widget for handle "
+                             << request->getWidgetHandle());
+                }
+
+                // Setting real attribute value
+                Attribute attr(*(iter->first));
+                attr.setType(Attribute::Type::WidgetParam);
+                iter2 = find_if(attributes->begin(),
+                                attributes->end(),
+                                BaseAttribute::UnaryPredicate(&attr));
+                Assert(iter2 != attributes->end() && "This should not happen, "
+                       "the attribute MUST be in attribute set");
+                (*iter2)->setUndetermind(false);
+                (*iter2)->setValue(attrValue);
+            }
+        }
+    }
+
+    /** clear query lists*/
+    resourceAttributesQuery.clear();
+    environmentAttributesQuery.clear();
+    subjectAttributesQuery.clear();
+    functionParamAttributesQuery.clear();
+    widgetParamAttributesQuery.clear();
+
+    return subjectReturn | resourceReturn | operationReturn | functionReturn;
+}
+
+/** create query lists */
+void PolicyInformationPoint::createQueries(AttributeSet* attributes)
+{
+    AttributeSet::const_iterator it;
+
+    enum Attribute::Type type;
+
+    /**iterate  all attributes and split them into adequate query  */
+    FOREACH (it, *attributes) {
+        type = (*it)->getType();
+
+        switch (type) {
+        case Attribute::Type::Subject:
+            subjectAttributesQuery.push_back(ATTRIBUTE((*it)->getName(),
+                                                       (*it)->getValue()));
+            break;
+
+        case Attribute::Type::Environment:
+            environmentAttributesQuery.push_back(ATTRIBUTE((*it)->getName(),
+                                                           (*it)->getValue()));
+            break;
+
+        case Attribute::Type::Resource:
+            resourceAttributesQuery.push_back(ATTRIBUTE((*it)->getName(),
+                                                        (*it)->getValue()));
+            break;
+
+        case Attribute::Type::FunctionParam:
+            functionParamAttributesQuery.push_back(ATTRIBUTE((*it)->getName(),
+                                                             (*it)->getValue()));
+            break;
+
+        case Attribute::Type::WidgetParam:
+            widgetParamAttributesQuery.push_back(ATTRIBUTE((*it)->getName(),
+                                                         (*it)->getValue()));
+            break;
+        default:
+            break;
+        }
+    }
+}
+
diff --git a/ace/engine/Rule.cpp b/ace/engine/Rule.cpp
new file mode 100644 (file)
index 0000000..c1703bb
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Rule.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#include <iostream>
+#include <dpl/log/log.h>
+
+#include <ace/Rule.h>
+
+void Rule::printData()
+{
+    std::cout << "Rule: effect: " << printEffect(this->effect) <<
+    " condition: " << this->condition;
+}
+
+std::string Rule::printEffect(const ExtendedEffect &effect) const
+{
+    switch (effect.getEffect()) {
+    case Deny:
+        return "Deny";
+    case PromptBlanket:
+        return "PromptBlanket";
+    case PromptOneShot:
+        return "PromptOneShot";
+    case PromptSession:
+        return "PromptSession";
+    case Permit:
+        return "Permit";
+    case Inapplicable:
+        return "Inapplicable";
+    case Error:
+        return "Error";
+    default:
+        return "ERROR";
+    }
+}
+
+ExtendedEffect Rule::evaluateRule(const AttributeSet * attrSet) const
+{
+    Attribute::MatchResult result = condition.evaluateCondition(attrSet);
+
+    if (result == Attribute::MatchResult::MRUndetermined) {
+        //        LogInfo("Rule is undetermined");
+        return ExtendedEffect(Undetermined);
+    } else if (result == Attribute::MatchResult::MRTrue) {
+        //       LogInfo("Rule effect "<<printEffect(effect));
+        return effect;
+    }
+    // LogInfo("Rule is inapplicable");
+    return Inapplicable;
+}
+
+
diff --git a/ace/engine/SettingsLogic.cpp b/ace/engine/SettingsLogic.cpp
new file mode 100644 (file)
index 0000000..2a19ce6
--- /dev/null
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       SettingsLogic.cpp
+ * @author     Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version    0.1
+ * @brief      SettingsLogic implementation
+ */
+
+#include <ace/SettingsLogic.h>
+
+#include <dpl/log/log.h>
+#include <dpl/foreach.h>
+
+#include <ace/Preference.h>
+
+using namespace AceDB;
+
+Preference SettingsLogic::findGlobalUserSettings(
+        const std::string &resource,
+        WidgetHandle handler)
+{
+    Preference p = AceDAO::getWidgetDevCapSetting(resource, handler);
+    if (PreferenceTypes::PREFERENCE_DEFAULT == p) {
+        return AceDAO::getDevCapSetting(resource);
+    } else {
+        return p;
+    }
+}
+
+Preference SettingsLogic::findGlobalUserSettings(
+        const Request &request)
+{
+    Request::DeviceCapabilitySet devset = request.getDeviceCapabilitySet();
+    Assert(!devset.empty() && "No device cap set in request");
+    return findGlobalUserSettings(
+        *(devset.begin()),
+        request.getWidgetHandle());
+}
+
+Preference SettingsLogic::getDevCapSetting(const std::string &resource)
+{
+    return AceDAO::getDevCapSetting(resource);
+}
+
+void SettingsLogic::getDevCapSettings(PreferenceMap *globalSettingsMap)
+{
+    AceDAO::getDevCapSettings(globalSettingsMap); // NULL check inside
+}
+
+
+void SettingsLogic::setDevCapSetting(const std::string &resource,
+                                       Preference preference)
+{
+    if (resource.empty()) {
+        LogInfo("WARNING: setting resource settings for empty resource name");
+    }
+
+    AceDAO::addResource(resource);
+
+    if (preference == PreferenceTypes::PREFERENCE_DEFAULT) {
+        return;
+    }
+
+    Assert((PreferenceTypes::PREFERENCE_PERMIT == preference ||
+            PreferenceTypes::PREFERENCE_DENY == preference ||
+            PreferenceTypes::PREFERENCE_BLANKET_PROMPT == preference ||
+            PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT == preference ||
+            PreferenceTypes::PREFERENCE_SESSION_PROMPT == preference));
+
+    AceDAO::setDevCapSetting(resource,preference);
+}
+
+void SettingsLogic::setAllDevCapSettings(
+    const std::list < std::pair < const std::string*,
+    Preference > > &resourcesList)
+{
+    std::list < std::pair < const std::string*,
+        Preference > >::const_iterator iter;
+    for (iter = resourcesList.begin(); iter != resourcesList.end(); ++iter) {
+        SettingsLogic::setDevCapSetting(*(iter->first), iter->second);
+    }
+}
+
+void SettingsLogic::removeDevCapSetting(const std::string &resource)
+{
+    AceDAO::removeDevCapSetting(resource);
+}
+
+void SettingsLogic::updateDevCapSetting(const std::string &resource,
+                                        Preference p)
+{
+    if (PreferenceTypes::PREFERENCE_DEFAULT == p) {
+        SettingsLogic::removeDevCapSetting(resource);
+    } else {
+        SettingsLogic::setDevCapSetting(resource, p);
+    }
+}
+
+Preference SettingsLogic::getWidgetDevCapSetting(
+        const std::string &resource,
+        WidgetHandle handler)
+{
+    return AceDAO::getWidgetDevCapSetting(resource, handler);
+}
+
+void SettingsLogic::getWidgetDevCapSettings(PermissionList *outputList)
+{
+    AceDAO::getWidgetDevCapSettings(outputList); // NULL check inside
+}
+
+
+void SettingsLogic::setWidgetDevCapSetting(
+        const std::string &resource,
+        WidgetHandle handler,
+        Preference preference)
+{
+    if (resource.empty()) {
+        LogError("Empty resource");
+        return;
+    }
+
+    LogDebug("userSetting, resource: " << resource <<
+             " app_id: " << handler);
+
+    AceDAO::addResource(resource);
+    SettingsLogic::removeWidgetDevCapSetting(resource, handler);
+
+    if (PreferenceTypes::PREFERENCE_DEFAULT == preference) {
+        return;
+    }
+
+    Assert((PreferenceTypes::PREFERENCE_PERMIT == preference ||
+            PreferenceTypes::PREFERENCE_DENY == preference ||
+            PreferenceTypes::PREFERENCE_BLANKET_PROMPT == preference ||
+            PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT == preference ||
+            PreferenceTypes::PREFERENCE_SESSION_PROMPT == preference));
+
+    AceDAO::setWidgetDevCapSetting(resource, handler, preference);
+}
+
+
+void SettingsLogic::setWidgetDevCapSettings(const PermissionList &permissionsList)
+{
+    FOREACH(i, permissionsList) {
+        SettingsLogic::setWidgetDevCapSetting(i->devCap,
+                i->appId,
+                i->access);
+    }
+}
+
+
+void SettingsLogic::removeWidgetDevCapSetting(const std::string &resource,
+                                              WidgetHandle handler)
+{
+    AceDAO::removeWidgetDevCapSetting(resource, handler);
+}
diff --git a/ace/engine/Subject.cpp b/ace/engine/Subject.cpp
new file mode 100644 (file)
index 0000000..57724be
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#include <dpl/log/log.h>
+#include <dpl/foreach.h>
+
+#include <ace/Subject.h>
+
+bool Subject::matchSubject(const AttributeSet *attrSet,
+        bool &isUndetermined) const
+{
+    bool result = true;
+    Attribute::MatchResult match = Attribute::MatchResult::MRUndetermined;
+
+    FOREACH(it, targetAttributes)
+    {
+        AttributeSet::const_iterator attr =
+            std::find_if(attrSet->begin(),
+                         attrSet->end(),
+                         AceDB::BaseAttribute::UnaryPredicate(&(*it)));
+        if (attr == attrSet->end()) {
+            LogError("Cannot find attribute value for " << *(it->getName()));
+            Assert(false &&
+                   "Attribute for subject hasn't been found."
+                   "It shoud not happen. This attribute should be undetermined,"
+                   "not missing");
+            result = false; //According to BONDI 1.0 for signle subject all attributes must match
+            isUndetermined = true;
+            break;
+        }
+
+        match = it->matchAttributes(&(*(*attr)));
+
+        if (match == Attribute::MatchResult::MRUndetermined) {
+            result = false;
+            isUndetermined = true;
+            ///          LogError("Subject doesn match and UNDETERMINED");
+            break; //According to BONDI 1.0 for signle subject all attributes must match
+        } else if (match == Attribute::MatchResult::MRFalse) {
+            result = false;
+            //            LogError("Subject doesn match and DETERMINED");
+            break; //According to BONDI 1.0 for signle subject all attributes must match
+        }
+    }
+
+    return result;
+}
+
+const std::list<Attribute>& Subject::getTargetAttributes() const
+{
+    return targetAttributes;
+}
+
diff --git a/ace/engine/TreeNode.cpp b/ace/engine/TreeNode.cpp
new file mode 100644 (file)
index 0000000..0171f4d
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#include <ace/TreeNode.h>
+#include <dpl/assert.h>
+#include <dpl/log/log.h>
+
+//Tree node destructor is a tricky part, only the original tree should remove the elements
+//release resources should be called when we want to destroy the whole tree
+TreeNode::~TreeNode()
+{
+    delete element;
+}
+
+//TODO release resources is releaseTheSubtree and delete the element
+void TreeNode::releaseResources()
+{
+    Assert(this != 0);
+    delete element;
+    std::list<TreeNode*>::iterator it = this->children.begin();
+    while (it != children.end()) {
+        (*it)->releaseResources();
+        ++it;
+    }
+    delete this;
+}
+
+int TreeNode::level = 0;
+
+std::ostream & operator<<(std::ostream & out,
+        const TreeNode * node)
+{
+    std::string tmp;
+
+    switch (node->getTypeID()) {
+    case TreeNode::Policy:
+        tmp = "Policy";
+        break;
+    case TreeNode::PolicySet:
+        tmp = "PolicySet";
+        break;
+    case TreeNode::Rule:
+        tmp = "Rule";
+        break;
+    default:
+        break;
+    }
+
+    out << "" << tmp << "-> children count: " << node->children.size() <<
+    ": " << std::endl;
+    AbstractTreeElement * el = node->getElement();
+    if (el != NULL) {
+        el->printData();
+    } else {
+        std::cout << "Empty element!" << std::endl;
+    }
+
+    return out;
+}
+
diff --git a/ace/engine/parser.cpp b/ace/engine/parser.cpp
new file mode 100644 (file)
index 0000000..76491f1
--- /dev/null
@@ -0,0 +1,749 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#include <memory>
+#include <functional>
+#include <string.h>
+#include <stdarg.h>
+#include <dpl/log/log.h>
+
+#include <ace/parser.h>
+#include <string.h>
+
+namespace {
+
+class ParserWarningLogger
+{
+  public:
+    void operator()(const std::string& logMsg)
+    {
+        LogWarning(logMsg);
+    }
+};
+
+class ParserErrorLogger
+{
+  public:
+    void operator()(const std::string& logMsg)
+    {
+        LogError(logMsg);
+    }
+};
+
+template <class Logger>
+void xmlLogFunction(void* /*ctx*/, const char *msg, ...)
+{
+    const int BUFFER_SIZE = 1024;
+    char buffer[BUFFER_SIZE];
+    buffer[BUFFER_SIZE - 1] = '\0';
+    Logger l;
+
+    va_list va;
+    va_start(va, msg);
+    vsnprintf(buffer, BUFFER_SIZE - 1, msg, va);
+    va_end(va);
+
+    std::string logmsg(buffer);
+    l(logmsg);
+}
+
+}
+
+const char *Parser::TOKEN_PARAM = "param:";
+
+Parser::Parser() :
+    ruleId(0),
+    reader(NULL),
+    root(NULL),
+    currentRoot(NULL),
+    currentSubject(NULL),
+    currentCondition(NULL),
+    currentAttribute(NULL),
+    currentText(NULL),
+    processingSignature(false),
+    canonicalizeOnce(false)
+{
+    processingSignature = true;
+    canonicalizeOnce = true;
+}
+
+Parser::~Parser()
+{
+    /* parse function destroys reader */
+    //  free(this->xmlFilename);
+}
+
+TreeNode* Parser::parse(const std::string& filename, const std::string& schema)
+{
+    if(root != NULL) {
+        root->releaseResources();
+        root = NULL;
+    }
+
+    LogDebug("Parser: opening file " << filename);
+
+    xmlDocPtr xmlDocument = xmlParseFile(filename.c_str());
+    if (!xmlDocument) {
+        LogError("Couldn't parse file " << filename);
+        return root;
+    }
+
+    std::unique_ptr <xmlDoc, std::function<void(xmlDoc*)> >
+        doc(xmlDocument, xmlFreeDoc);
+
+    xmlSchemaParserCtxtPtr xmlSchemaParserContext =
+        xmlSchemaNewParserCtxt(schema.c_str());
+
+    if (!xmlSchemaParserContext) {
+        LogError("Couldn't load xml schema: " << schema);
+        return root;
+    }
+
+    std::unique_ptr <
+                     xmlSchemaParserCtxt,
+                     std::function<void(xmlSchemaParserCtxt*)> >
+                     schemaContext(
+                                   xmlSchemaParserContext,
+                                   xmlSchemaFreeParserCtxt);
+
+    LogDebug("Setting callbacks");
+
+    xmlSchemaSetParserErrors(
+        schemaContext.get(),
+        static_cast<xmlValidityErrorFunc>
+            (&xmlLogFunction<ParserErrorLogger>),
+        static_cast<xmlValidityWarningFunc>
+            (&xmlLogFunction<ParserWarningLogger>),
+        NULL);
+
+    xmlSchemaPtr xmlSchema = xmlSchemaParse(schemaContext.get());
+
+    if (!xmlSchema) {
+        LogError("Couldn't parse xml schema: " << xmlSchema);
+        return root;
+    }
+
+    xmlSchemaValidCtxtPtr xmlValidContext = xmlSchemaNewValidCtxt(xmlSchema);
+
+    if (!xmlValidContext) {
+        LogError("Couldn't create validation context!");
+        xmlSchemaFree(xmlSchema);
+        return root;
+    }
+
+    std::unique_ptr <
+                     xmlSchemaValidCtxt,
+                     std::function<void(xmlSchemaValidCtxt*)> >
+                     schemaValidContext(
+                                        xmlValidContext,
+                                        xmlSchemaFreeValidCtxt);
+
+    xmlSchemaSetValidErrors(
+        schemaValidContext.get(),
+        static_cast<xmlValidityErrorFunc>
+            (&xmlLogFunction<ParserErrorLogger>),
+        static_cast<xmlValidityWarningFunc>
+            (&xmlLogFunction<ParserWarningLogger>),
+        NULL);
+
+    xmlSchemaSetValidOptions(
+                             schemaValidContext.get(),
+                             XML_SCHEMA_VAL_VC_I_CREATE);
+
+    bool result =
+        (xmlSchemaValidateDoc(
+                              schemaValidContext.get(),
+                              xmlDocument) == 0 ? true : false);
+
+    xmlSchemaFree(xmlSchema);
+
+    if (!result) {
+        LogError("Couldn't validate policy file: " << filename <<
+                 " against xml schema: " << schema);
+
+        return root;
+    }
+
+    LogInfo("Policy file: " << filename << " validated!");
+
+    xmlTextReaderPtr xmlReader = xmlReaderWalker(xmlDocument);
+
+    //[CR] consider using ASSERT/DASSERT
+    if (NULL == xmlReader) {
+        LogError("Error, xml reader cannot be created. Probably xml file is missing (opening file " << filename << ")");
+        return root;
+    }
+
+    std::unique_ptr <xmlTextReader, std::function<void(xmlTextReader*)> >
+         reader(xmlReader, xmlFreeTextReader);
+
+    int ret;
+    ret = xmlTextReaderRead(reader.get());
+    while (ret == 1) {
+        std::unique_ptr<xmlChar, std::function<void(xmlChar*)> >
+            name(xmlTextReaderName(reader.get()), xmlFree);
+
+        if (!strcmp("policy-set", (const char *)name.get())) {
+            processingSignature = false;
+        } else if (!strcmp("SignedInfo",
+                           (const char *)name.get()) && canonicalizeOnce) {
+            #if 0 //TODO I think we don't need canonicalization in ACE only in PM,
+            //we have to  verify it tough
+            extractNodeToFile(reader, "output.xml");
+            //TODO we should be able to handle more than one canonicalization algorithm
+            canonicalize("output.xml", "canon.xml", Canonicalization::C14N);
+            canonicalizeOnce = false;
+            #endif
+        }
+        //Do not process signature of xml file
+        if(!processingSignature) {
+            processNode(reader.get());
+        }
+        ret = xmlTextReaderRead(reader.get());
+    }
+
+    if (ret != 0) {
+        LogError("Error while parsing XML file");
+        if (root) {
+            root->releaseResources();
+            root = NULL;
+        }
+    }
+
+    return root;
+}
+
+void Parser::processNode(xmlTextReaderPtr reader)
+{
+    //TODO this is interesting, xmlTextReaderNodeType returns int but I am pretty sure
+    //those integers coresponds to xmlReaderTypes
+    xmlReaderTypes type =
+        static_cast<xmlReaderTypes>(xmlTextReaderNodeType(reader));
+
+    switch (type) {
+    //Start element
+    case XML_READER_TYPE_ELEMENT:
+        startNodeHandler(reader);
+        break;
+    //End element
+    case XML_READER_TYPE_END_ELEMENT:
+        endNodeHandler(reader);
+        break;
+    //Text element
+    case XML_READER_TYPE_TEXT:
+        textNodeHandler(reader);
+        break;
+    default:
+        //Do not handle other xml tags
+        break;
+    }
+}
+
+void Parser::startNodeHandler(xmlTextReaderPtr reader)
+{
+    xmlChar *name = xmlTextReaderName(reader);
+
+    switch (*name) {
+    case 'p':     //policy and policy-set
+        if (*(name + 6) == 0) {
+            handlePolicy(reader, TreeNode::Policy);
+        } else {
+            handlePolicy(reader, TreeNode::PolicySet);
+        }
+        break;
+    case 'r':     //rule and resource-match
+        if (*(name + 1) == 'u') {
+            handleRule(reader);
+        } else if (*(name + 9) == 'm') {
+            handleMatch(reader, Attribute::Type::Resource);
+        } else {
+            handleAttr(reader);
+        }
+        break;
+    case 's':     //subject and subject-match
+        if (*(name + 7) == 0) {
+            handleSubject();
+        } else if (*(name + 8) == 'm') { //subject match
+            handleSubjectMatch(reader);
+        } else {  //subject attr
+            handleAttr(reader);
+        }
+        break;
+    case 'c':    //condition
+        handleCondition(reader);
+        break;
+    case 'e':    //environment-match
+        if (*(name + 12) == 'm') {
+            handleMatch(reader, Attribute::Type::Environment);
+        } else {  //env-attr
+            handleAttr(reader);
+        }
+        break;
+    }
+    xmlFree(name);
+}
+
+void Parser::endNodeHandler(xmlTextReaderPtr reader)
+{
+    xmlChar *name = xmlTextReaderName(reader);
+
+    switch (*name) {
+    case 'p':     //policy and policy-set
+        //Restore old root
+        currentRoot = currentRoot->getParent();
+        break;
+    case 'r':     //Rule and resource match
+        if (*(name + 1) == 'u') { //Rule
+            currentRoot = currentRoot->getParent();
+        } else {  //Resource-match
+            consumeCurrentText();     //consume text if any available
+            consumeCurrentAttribute();     //consume attribute
+        }
+        break;
+    case 's':     //subject and subject-match
+        if (*(name + 7) == 0) { //handle subject
+            consumeCurrentSubject();
+        } else if (*(name + 8) == 'm') { //handle subject match
+            consumeCurrentText();
+            consumeSubjectMatch();
+        }
+        //Subject-match end doesn't require handling
+        break;
+    case 'c':    //condition
+        consumeCurrentCondition();
+        break;
+    case 'e':    //environment-match
+        consumeCurrentText();     //consume text if any available
+        consumeCurrentAttribute();     //consume attribute
+        break;
+    }
+    xmlFree(name);
+}
+
+void Parser::textNodeHandler(xmlTextReaderPtr reader)
+{
+    delete currentText;
+    xmlChar * text = xmlTextReaderValue(reader);
+    Assert(text != NULL && "Parser couldn't parse PCDATA");
+
+    currentText = new std::string(reinterpret_cast<const char * >(text));
+    trim(currentText);
+    xmlFree(text);
+}
+
+void Parser::handlePolicy(xmlTextReaderPtr reader,
+        TreeNode::TypeID type)
+{
+    Policy::CombineAlgorithm algorithm;
+
+    //Get first attribute
+    xmlChar * combAlg = xmlTextReaderGetAttribute(reader, BAD_CAST("combine"));
+
+    Assert(combAlg != NULL && "Parser error while getting attributes");
+    algorithm = convertToCombineAlgorithm(combAlg);
+
+    //Create TreeNode element
+    Policy * policy = NULL;
+    if (type == TreeNode::Policy) {
+        policy = new Policy();
+    } else {
+        policy = new PolicySet();
+    }
+    policy->setCombineAlgorithm(algorithm);
+    TreeNode * node = new TreeNode(currentRoot, type, policy);
+    //Add new tree node to current's root children set
+    if (currentRoot != NULL) {
+        currentRoot->addChild(node);
+    }
+
+    //Switch the current root to the new node
+    if (!xmlTextReaderIsEmptyElement(reader)) {
+        //Current root switching is necessary only if tag is not empty
+        currentRoot = node;
+    }
+    if (root == NULL) {
+        root = currentRoot;
+    }
+
+    if (NULL == currentRoot) {
+        node->releaseResources();
+    }
+
+    xmlFree(combAlg);
+}
+
+void Parser::handleRule(xmlTextReaderPtr reader)
+{
+    ExtendedEffect effect(Inapplicable);
+
+    //[CR] create macros for attribute names
+    xmlChar * eff = xmlTextReaderGetAttribute(reader, BAD_CAST("effect")); //get the rule attribute
+
+    Assert(eff != NULL && "Parser error while getting attributes");
+    effect = convertToEffect(eff);
+
+    Rule * rule = NULL;
+    rule = new Rule();
+    rule->setEffect(effect);
+
+    TreeNode * node = new TreeNode(currentRoot, TreeNode::Rule, rule);
+    //Add new tree node to current's root children set
+    if (currentRoot != NULL) { //
+        currentRoot->addChild(node);
+    }
+
+    if (!xmlTextReaderIsEmptyElement(reader)) {
+        currentRoot = node;
+    }
+
+    if (NULL == currentRoot) {
+        node->releaseResources();
+    }
+
+    xmlFree(eff);
+}
+
+void Parser::handleSubject()
+{
+    currentSubject = new Subject();
+    //TODO what about empty subject tag
+}
+
+void Parser::handleCondition(xmlTextReaderPtr reader)
+{
+    Condition::CombineType combineType = Condition::AND;
+
+    xmlChar * combine = xmlTextReaderGetAttribute(reader, BAD_CAST("combine")); //get the rule attribute
+
+    Assert(combine != NULL && "Parser error while getting attributes");
+
+    combineType = *combine == 'a' ? Condition::AND : Condition::OR;
+
+    Condition * condition = new Condition();
+    condition->setCombineType(combineType);
+    condition->setParent(currentCondition);
+
+    currentCondition = condition;
+    xmlFree(combine);
+    //TODO what about empty condition tag?
+}
+
+//Subject match is handled differently than resource or environment match
+//Because it cannot have any children tags and can only include PCDATA
+void Parser::handleSubjectMatch(xmlTextReaderPtr reader)
+{
+    //processing Subject
+    int attributes = xmlTextReaderAttributeCount(reader);
+
+    xmlChar * func = NULL;
+    xmlChar * value = NULL;
+    xmlChar * attrName = xmlTextReaderGetAttribute(reader, BAD_CAST("attr")); //get the first attribute
+
+    if (attributes == 2) {
+        //match attribute ommited, text value will be used
+        func = xmlTextReaderGetAttribute(reader, BAD_CAST("func"));
+    } else if (attributes == 3) {
+        value = xmlTextReaderGetAttribute(reader, BAD_CAST("match"));
+        func = xmlTextReaderGetAttribute(reader, BAD_CAST("func"));
+    } else {
+        Assert(false && "Wrong XML file format");
+    }
+
+    // creating temporiary object is not good idea
+    // but we have no choice untill Attribute have constructor taking std::string*
+    std::string temp(reinterpret_cast<const char *>(attrName));
+    Attribute * attr = new Attribute(&temp, convertToMatchFunction(
+                                         func), Attribute::Type::Subject);
+    if (value != NULL) { //add value of the attribute if possible
+        //[CR] consider create Attribute::addValue(char *) function
+        std::string temp(reinterpret_cast<const char *>(value));
+        attr->addValue(&temp);
+    }
+    currentAttribute = attr;
+
+    if (xmlTextReaderIsEmptyElement(reader)) {
+        Assert(value != NULL && "XML file format is wrong");
+        //Attribute value is required to obtain the match value easier
+        consumeSubjectMatch(value);
+    }
+
+    if (attributes == 2 || attributes == 3) {
+        xmlFree(func);
+    }
+    xmlFree(value);
+    xmlFree(attrName);
+}
+
+void Parser::handleMatch(xmlTextReaderPtr reader,
+        Attribute::Type type)
+{
+    int attributes = xmlTextReaderAttributeCount(reader);
+
+    xmlChar * func = NULL;
+    xmlChar * value = NULL;
+    xmlChar * attrName = xmlTextReaderGetAttribute(reader, BAD_CAST("attr")); //get the first attribute
+
+    if (attributes == 2) {
+        //match attribute ommited, text value will be used
+        func = xmlTextReaderGetAttribute(reader, BAD_CAST("func"));
+        //the content may be resource-attr or PCDATA
+    } else if (attributes == 3) {
+        value = xmlTextReaderGetAttribute(reader, BAD_CAST("match"));
+        func = xmlTextReaderGetAttribute(reader, BAD_CAST("func"));
+    } else {
+        Assert(false && "Wrong XML file format");
+    }
+
+    // FunctionParam type is sybtype of Resource.
+    // FunctionParam is used to storage attriburess of call functions.
+    if (0 ==
+        xmlStrncmp(attrName, BAD_CAST(TOKEN_PARAM),
+                   xmlStrlen(BAD_CAST(TOKEN_PARAM))) && type ==
+        Attribute::Type::Resource) {
+        type = Attribute::Type::FunctionParam;
+    }
+
+    std::string temp(reinterpret_cast<const char*>(attrName));
+    Attribute * attr = new Attribute(&temp, convertToMatchFunction(func), type);
+    currentAttribute = attr;
+
+    if (xmlTextReaderIsEmptyElement(reader)) {
+        Assert(value != NULL && "XML is currupted");
+        std::string tempVal(reinterpret_cast<const char*>(value));
+        currentAttribute->addValue(&tempVal);
+        consumeCurrentAttribute();
+    }
+
+    if (attributes == 2 || attributes == 3) {
+        xmlFree(func);
+    }
+    xmlFree(value);
+    xmlFree(attrName);
+}
+
+Policy::CombineAlgorithm Parser::convertToCombineAlgorithm(xmlChar* algorithm)
+{
+    switch (*algorithm) {
+    case 'f':
+        if (*(algorithm + 6) == 'a') { //first applicable
+            return Policy::FirstApplicable;
+        }
+        return Policy::FirstTargetMatching;
+    case 'd':
+        return Policy::DenyOverride;
+    case 'p':
+        return Policy::PermitOverride;
+    default:
+        Assert(false && "Wrong combine algorithm name");
+        return Policy::DenyOverride;
+    }
+}
+
+ExtendedEffect Parser::convertToEffect(xmlChar *effect)
+{
+    switch (*effect) {
+    case 'd':     //deny
+        return Deny;
+        break;
+    case 'p':
+        //permit, prompt-blanket, prompt-session, prompt-oneshot
+        if (*(effect + 1) == 'e') {
+            return ExtendedEffect(Permit, ruleId++);
+        }
+        switch (*(effect + 7)) {
+        case 'b':
+            return ExtendedEffect(PromptBlanket, ruleId++);
+        case 's':
+            return ExtendedEffect(PromptSession, ruleId++);
+        case 'o':
+            return ExtendedEffect(PromptOneShot, ruleId++);
+        default:
+            Assert(false && "Effect is Error");
+            return ExtendedEffect();
+        }
+        break;
+    default:
+        Assert(false && "Effect is Error");
+        return ExtendedEffect();
+    }
+    //return ExtendedEffect(Inapplicable);
+}
+
+Attribute::Match Parser::convertToMatchFunction(xmlChar * func)
+{
+    if (func == NULL) {
+        LogError("[ERROR] match function value is NULL");
+        return Attribute::Match::Error;
+    }
+
+    if (*func == 'g') {
+        return Attribute::Match::Glob;
+    } else if (*func == 'e') {
+        return Attribute::Match::Equal;
+    } else if (*func == 'r') {
+        return Attribute::Match::Regexp;
+    } else {
+        LogError("[ERROR] match function value is NULL");
+        return Attribute::Match::Error;
+    }
+    //Assert(false);
+}
+
+void Parser::handleAttr(xmlTextReaderPtr reader)
+{
+    xmlChar * attrValue = xmlTextReaderGetAttribute(reader, BAD_CAST("attr")); //get the first attribute
+    Assert(attrValue != NULL && "Error while obtaining attribute");
+
+    std::string temp(reinterpret_cast<const char*>(attrValue));
+    currentAttribute->addValue(&temp);
+
+    xmlFree(attrValue);
+}
+
+void Parser::consumeCurrentText()
+{
+    Assert(currentText != NULL);
+    currentAttribute->addValue(currentText);
+    delete currentText;
+
+    currentText = NULL;
+}
+
+void Parser::consumeCurrentAttribute()
+{
+    Assert(currentAttribute != NULL);
+
+    currentCondition->addAttribute(*currentAttribute);
+    delete currentAttribute;
+
+    currentAttribute = NULL;
+}
+
+void Parser::consumeCurrentSubject()
+{
+    Policy * policy = dynamic_cast<Policy *>(currentRoot->getElement());
+    Assert(policy != NULL);
+    policy->addSubject(currentSubject);
+    //TODO maybe keep subjects not subject pointers in Policies and consume subjects here
+    currentSubject = NULL;
+}
+
+void Parser::consumeCurrentCondition()
+{
+    Condition * temp = NULL;
+    if (currentCondition != NULL) {
+        if (currentCondition->getParent() != NULL) { //Condition is a child of another condition
+            currentCondition->getParent()->addCondition(*currentCondition);
+        } else { //Condition parent is a Rule
+            Rule * rule = dynamic_cast<Rule *>(currentRoot->getElement());
+            Assert(rule != NULL);
+            rule->setCondition(*currentCondition);
+        }
+        temp = currentCondition->getParent();
+        delete currentCondition;
+    }
+    currentCondition = temp;  //switch current condition ( it may be switched to NULL if condition's parent was rule
+}
+
+void Parser::consumeSubjectMatch(xmlChar * value)
+{
+    Assert(
+        currentAttribute != NULL &&
+        "consuming subject match without attribute set");
+
+    if (currentSubject != NULL) {
+        currentSubject->addNewAttribute(*currentAttribute);
+        //[CR] matching/modyfing functions transform uri.host to uri ( etc. ) so strncmp is not needed, string equality will do
+        if (!strncmp(currentAttribute->getName()->c_str(), "uri",
+                     3) ||
+            !strncmp(currentAttribute->getName()->c_str(), "id", 2)) {
+            if (value != NULL) {
+                currentSubject->setSubjectId(reinterpret_cast<const char *>(
+                                                 value));
+            } else if (currentAttribute->getValue()->size()) {
+                currentSubject->setSubjectId(
+                    currentAttribute->getValue()->front());
+            } else {
+                Assert(false);
+            }
+        }
+    } else if (currentCondition != NULL) {
+        currentCondition->addAttribute(*currentAttribute);
+    }
+
+    delete currentAttribute;
+    currentAttribute = NULL;
+}
+
+void Parser::trim(std::string * str)
+{
+    std::string::size_type pos = str->find_last_not_of(whitespaces);
+    if (pos != std::string::npos) {
+        str->erase(pos + 1);
+        pos = str->find_first_not_of(whitespaces);
+        if (pos != std::string::npos) {
+            str->erase(0, pos);
+        }
+    } else {
+        str->erase(str->begin(), str->end());
+        LogInfo("Warning, empty string as attribute value");
+    }
+}
+
+// KW void Parser::canonicalize(const char * input, const char * output, CanonicalizationAlgorithm canonicalizationAlgorithm){
+// KW
+// KW     xmlDocPtr       doc =  xmlParseFile(input);
+// KW     //xmlDocDump(stdout, doc);
+// KW
+// KW     if(doc == NULL)
+// KW     {
+// KW         LogError("Canonicalization error, cannot parser xml file");
+// KW     }
+// KW
+// KW
+// KW     int mode = -1;
+// KW     if(canonicalizationAlgorithm == C14N)
+// KW     {
+// KW         mode = 0;
+// KW     }
+// KW     else if(canonicalizationAlgorithm == C14NEXCLUSIVE)
+// KW     {
+// KW         mode = 1;
+// KW     }
+// KW
+// KW
+// KW     xmlC14NDocSave(doc, NULL, mode, NULL, 0, output, 0);
+// KW
+// KW     xmlFreeDoc(doc);
+// KW
+// KW }
+
+// KW int Parser::extractNodeToFile(xmlTextReaderPtr reader, const char * filename){
+// KW
+// KW        xmlNodePtr node = xmlTextReaderExpand(reader);
+// KW        xmlBufferPtr buff = xmlBufferCreate();
+// KW        xmlNodeDump(buff, node->doc, node, 0, 0);
+// KW        FILE * file = fopen(filename, "w");
+// KW        if(file == NULL){
+// KW            LogError("Error while trying to open file "<<filename);
+// KW            return -1;
+// KW        }
+// KW        int ret = xmlBufferDump(file, buff);
+// KW        fclose(file);
+// KW        xmlBufferFree(buff);
+// KW        return ret;
+// KW
+// KW }
+
diff --git a/ace/include/ace-dao-ro/AceDAOConversions.h b/ace/include/ace-dao-ro/AceDAOConversions.h
new file mode 100644 (file)
index 0000000..e91c850
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       AceDAOConversions.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef WRT_ACE_DAO_CONVERSIONS_H_
+#define WRT_ACE_DAO_CONVERSIONS_H_
+
+#include <dpl/string.h>
+#include <ace-dao-ro/BaseAttribute.h>
+
+namespace AceDB {
+namespace AceDaoConversions {
+
+DPL::String convertToHash(const BaseAttributeSet &attributes);
+
+}
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/AceDAOReadOnly.h b/ace/include/ace-dao-ro/AceDAOReadOnly.h
new file mode 100644 (file)
index 0000000..cda83c8
--- /dev/null
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       AceDAOReadOnly.h
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACE_DAO_READ_ONLY_H_
+#define ACE_DAO_READ_ONLY_H_
+
+#include <map>
+
+#include <openssl/md5.h>
+#include <dpl/string.h>
+#include <dpl/exception.h>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace-dao-ro/BaseAttribute.h>
+#include <ace-dao-ro/BasePermission.h>
+#include <ace-dao-ro/AppTypes.h>
+#include <ace-dao-ro/IRequest.h>
+#include <ace/PolicyEffect.h>
+#include <ace/PolicyResult.h>
+#include <ace/PromptDecision.h>
+#include <ace-dao-ro/common_dao_types.h>
+
+namespace AceDB {
+
+typedef std::map<DPL::String, bool> RequestedDevCapsMap;
+typedef DPL::String FeatureName;
+typedef std::vector<FeatureName> FeatureNameVector;
+
+class AceDAOReadOnly
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, DatabaseError)
+    };
+
+    AceDAOReadOnly() {}
+
+    static void attachToThreadRO(void);
+    static void attachToThreadRW(void);
+    static void detachFromThread(void);
+
+    // policy effect/decision
+    static OptionalExtendedPolicyResult getPolicyResult(
+            const BaseAttributeSet &attributes);
+
+    static OptionalExtendedPolicyResult getPolicyResult(
+        const DPL::String &attrHash);
+
+    static OptionalCachedPromptDecision getPromptDecision(
+            WidgetHandle widgetHandle,
+            int ruleId);
+
+    // resource settings
+    static PreferenceTypes getDevCapSetting(const std::string &resource);
+    static void getDevCapSettings(PreferenceTypesMap *preferences);
+
+    // user settings
+    static void getWidgetDevCapSettings(BasePermissionList *permissions);
+    static PreferenceTypes getWidgetDevCapSetting(
+            const std::string &resource,
+            WidgetHandle handler);
+
+    static void getAttributes(BaseAttributeSet *attributes);
+
+    // Getter for device capabilities that are requested in widgets config.
+    //
+    // Additional boolean flag means whether widget will always get
+    // (at launch) the SMACK permissions needed to use the device cap).
+    //
+    // 'permissions' is the map of device cap names and smack status for
+    // given widget handle.
+    static void getRequestedDevCaps(
+        WidgetHandle widgetHandle,
+        RequestedDevCapsMap *permissions);
+
+    static void getAcceptedFeature(
+        WidgetHandle widgetHandle,
+        FeatureNameVector *featureVector);
+
+    static WidgetHandleList getHandleList();
+
+    static AppTypes getWidgetType(WidgetHandle handle);
+    static std::string getVersion(WidgetHandle widgetHandle);
+    static std::string getAuthorName(WidgetHandle widgetHandle);
+    static std::string getGUID(WidgetHandle widgetHandle);
+
+    static WidgetCertificateCNList getKeyCommonNameList(
+            WidgetHandle widgetHandle,
+            WidgetCertificateData::Owner owner,
+            WidgetCertificateData::Type type);
+    static FingerPrintList getKeyFingerprints(
+            WidgetHandle widgetHandle,
+            WidgetCertificateData::Owner owner,
+            WidgetCertificateData::Type type);
+
+    static std::string getShareHref(WidgetHandle widgetHandle);
+    static bool isWidgetInstalled(WidgetHandle handle);
+
+  protected:
+    static int promptDecisionToInt(PromptDecision decision);
+    static PromptDecision intToPromptDecision(int decision);
+    static int appTypeToInt(AppTypes app_type);
+    static AppTypes intToAppType(int app_type);
+};
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/AceDAOUtilities.h b/ace/include/ace-dao-ro/AceDAOUtilities.h
new file mode 100644 (file)
index 0000000..cae59a4
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       AceDAOUtil.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef WRT_ACE_DAO_UTILITIES_H_
+#define WRT_ACE_DAO_UTILITIES_H_
+
+#include <dpl/db/thread_database_support.h>
+#include <ace-dao-ro/BaseAttribute.h>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace-dao-ro/VerdictTypes.h>
+#include <orm_generator_ace.h>
+
+namespace AceDB {
+
+namespace AceDaoUtilities {
+
+BaseAttribute::Type intToAttributeType(int val);
+int attributeTypeToInt(BaseAttribute::Type type);
+int preferenceToInt(PreferenceTypes p);
+PreferenceTypes intToPreference(int p);
+VerdictTypes intToVerdict(int v);
+int verdictToInt(VerdictTypes v);
+bool getSubjectByUri(const std::string &uri,
+                     DPL::DB::ORM::ace::AceSubject::Row &row);
+bool getResourceByUri(const std::string &uri,
+                      DPL::DB::ORM::ace::AceDevCap::Row &row);
+
+extern DPL::DB::ThreadDatabaseSupport m_databaseInterface;
+
+}
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/AceDatabase.h b/ace/include/ace-dao-ro/AceDatabase.h
new file mode 100644 (file)
index 0000000..d5b2838
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    AceDatabase.h
+ * @author  Lukasz Marek (l.marek@samsung.com)
+ * @version 1.0
+ * @brief   This file contains the declaration of ace database
+ */
+
+#ifndef WRT_ENGINE_SRC_ACCESS_CONTROL_ACE_DATABASE_H
+#define WRT_ENGINE_SRC_ACCESS_CONTROL_ACE_DATABASE_H
+
+#include <dpl/thread.h>
+#include <dpl/mutex.h>
+
+extern DPL::Mutex g_aceDbQueriesMutex;
+
+#define ACE_DB_INTERNAL(tlsCommand, InternalType, interface)                 \
+    static DPL::ThreadLocalVariable<InternalType> *tlsCommand ## Ptr = NULL; \
+    {                                                                        \
+        DPL::Mutex::ScopedLock lock(&g_aceDbQueriesMutex);                   \
+        if (!tlsCommand ## Ptr) {                                            \
+            static DPL::ThreadLocalVariable<InternalType> tmp;               \
+            tlsCommand ## Ptr = &tmp;                                        \
+        }                                                                    \
+    }                                                                        \
+    DPL::ThreadLocalVariable<InternalType> &tlsCommand = *tlsCommand ## Ptr; \
+    if (tlsCommand.IsNull()) { tlsCommand = InternalType(interface); }
+
+#define ACE_DB_SELECT(name, type, interface) \
+    ACE_DB_INTERNAL(name, type::Select, interface)
+
+#define ACE_DB_INSERT(name, type, interface) \
+    ACE_DB_INTERNAL(name, type::Insert, interface)
+
+#define ACE_DB_UPDATE(name, type, interface) \
+    ACE_DB_INTERNAL(name, type::Update, interface)
+
+#define ACE_DB_DELETE(name, type, interface) \
+    ACE_DB_INTERNAL(name, type::Delete, interface)
+
+
+#endif // WRT_ENGINE_SRC_ACCESS_CONTROL_ACE_DATABASE_H
diff --git a/ace/include/ace-dao-ro/AppTypes.h b/ace/include/ace-dao-ro/AppTypes.h
new file mode 100644 (file)
index 0000000..b8b56fa
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       AppTypes.h
+ * @author     Tomasz Swierczek (t.swierczek@samsung.com)
+ */
+
+#ifndef ACCESS_CONTROL_DAO_APPTYPES_H_
+#define ACCESS_CONTROL_DAO_APPTYPES_H_
+
+namespace AceDB{
+
+enum class AppTypes
+{
+    Unknown,
+    WAC20,
+    Tizen
+};
+
+}
+
+#endif // ACCESS_CONTROL_DAO_APPTYPES_H_
diff --git a/ace/include/ace-dao-ro/BaseAttribute.h b/ace/include/ace-dao-ro/BaseAttribute.h
new file mode 100644 (file)
index 0000000..2b4ff89
--- /dev/null
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       IAttribute.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_BASEATTRIBUTE_H_
+#define ACCESS_CONTROL_DAO_BASEATTRIBUTE_H_
+
+#include <list>
+#include <set>
+#include <string>
+#include <memory>
+#include <dpl/assert.h>
+
+namespace AceDB {
+
+class BaseAttribute;
+typedef std::shared_ptr<BaseAttribute> BaseAttributePtr;
+
+class BaseAttribute
+{
+
+  public:
+    /**
+     * Types of attributes
+     */
+    enum class Type { Subject, Environment, Resource, FunctionParam,
+                      WidgetParam, Undefined };
+
+    struct UnaryPredicate
+    {
+      public:
+        UnaryPredicate(const AceDB::BaseAttribute *comp = NULL) :
+            m_priv(comp)
+        {
+        }
+
+        bool operator()(const AceDB::BaseAttributePtr &comp)
+        {
+            Assert(m_priv != NULL);
+            if (m_priv->getName()->compare(*comp->getName()) != 0) {
+                return false;
+            }
+            return m_priv->getType() == comp->getType();
+        }
+
+        bool operator()(const AceDB::BaseAttributePtr &comp1,
+                        const AceDB::BaseAttributePtr &comp2)
+        {
+            if (comp1->getType() != comp2->getType()) {
+                return comp1->getType() < comp2->getType();
+            }
+            return comp1->getName()->compare(*comp2->getName()) < 0;
+        }
+
+      private:
+          const AceDB::BaseAttribute *m_priv;
+    };
+
+  public:
+    BaseAttribute() :
+        m_typeId(Type::Undefined),
+        m_undetermindState(false)
+    {}
+
+    virtual void setName(const std::string& name)
+    {
+        m_name = name;
+    }
+    virtual void setName(const std::string* name)
+    {
+        m_name = *name;
+    }
+
+    virtual void setType(const Type& type)
+    {
+        m_typeId = type;
+    }
+    virtual Type getType() const
+    {
+        return m_typeId;
+    }
+
+    virtual const std::string* getName() const
+    {
+        return &m_name;
+    }
+
+    //TODO think
+    virtual void setUndetermind(bool tmp)
+    {
+        m_undetermindState = tmp;
+    }
+    virtual bool isUndetermind() const
+    {
+        return m_undetermindState;
+    }
+    virtual std::list<std::string> * getValue() const
+    {
+        return const_cast<std::list<std::string>* >(&value);
+    }
+    virtual bool isValueEmpty() const
+    {
+        return value.empty();
+    }
+
+    virtual void setValue(const std::list<std::string>& arg)
+    {
+        value = arg;
+    }
+
+    virtual ~BaseAttribute()
+    {
+    }
+
+    static const char * typeToString(Type type);
+
+    virtual std::string toString() const;
+
+  protected:
+    std::string m_name;
+    Type m_typeId;
+    bool m_undetermindState;
+    std::list<std::string> value; //string bag list
+};
+
+typedef std::set<BaseAttributePtr, BaseAttribute::UnaryPredicate> BaseAttributeSet;
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/BasePermission.h b/ace/include/ace-dao-ro/BasePermission.h
new file mode 100644 (file)
index 0000000..103cc58
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       IPermission.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_BASEPERMISSION_H_
+#define ACCESS_CONTROL_DAO_BASEPERMISSION_H_
+
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace-dao-ro/common_dao_types.h>
+
+namespace AceDB{
+
+struct BasePermission
+{
+    BasePermission(WidgetHandle handler,
+                   const std::string& devCap,
+                   PreferenceTypes accessAllowed) :
+        appId(handler),
+        devCap(devCap),
+        access(accessAllowed)
+    {
+    }
+
+    WidgetHandle appId;
+    std::string devCap;
+    PreferenceTypes access;
+};
+
+typedef std::list<BasePermission> BasePermissionList;
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/IRequest.h b/ace/include/ace-dao-ro/IRequest.h
new file mode 100644 (file)
index 0000000..2975b8b
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       IRequest.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_IREQUEST_H_
+#define ACCESS_CONTROL_DAO_IREQUEST_H_
+
+namespace AceDB{
+
+class IRequest
+{
+public:
+    virtual ~IRequest(){}
+};
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/PreferenceTypes.h b/ace/include/ace-dao-ro/PreferenceTypes.h
new file mode 100644 (file)
index 0000000..0f96dc5
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       PreferenceTypes.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_PREFERENCETYPES_H_
+#define ACCESS_CONTROL_DAO_PREFERENCETYPES_H_
+
+#include <map>
+#include <string>
+
+namespace AceDB{
+
+enum class PreferenceTypes
+{
+    PREFERENCE_PERMIT,
+    PREFERENCE_DENY,
+    PREFERENCE_DEFAULT,
+    PREFERENCE_BLANKET_PROMPT,
+    PREFERENCE_SESSION_PROMPT,
+    PREFERENCE_ONE_SHOT_PROMPT
+};
+
+
+typedef std::map<std::string, PreferenceTypes> PreferenceTypesMap;
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/PromptModel.h b/ace/include/ace-dao-ro/PromptModel.h
new file mode 100644 (file)
index 0000000..8819eae
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/* @file        PromptModel.h
+ * @author      Justyna Mejzner (j.kwiatkowsk@samsung.com)
+ * @author      Jaroslaw Osmanski (j.osmanski@samsung.com)
+ * @version     1.0
+ *
+ */
+
+#ifndef WRT_SRC_ACCESSCONTROL_ENGINE_PROMPT_MODEL_H_
+#define WRT_SRC_ACCESSCONTROL_ENGINE_PROMPT_MODEL_H_
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <dpl/optional_typedefs.h>
+
+namespace Prompt {
+typedef std::vector<std::string> ButtonLabels;
+
+class PromptLabels
+{
+public:
+    PromptLabels(int promptType,
+                 const Prompt::ButtonLabels& questionLabel,
+                 const std::string& mainLabel);
+    DPL::OptionalString getCheckLabel() const;
+    bool isAllowed(const size_t buttonNumber) const;
+    int getPromptType() const;
+    const ButtonLabels& getButtonLabels() const;
+    const std::string& getMainLabel() const;
+
+private:
+    int m_promptType;
+    ButtonLabels m_buttonLabels;
+    std::string m_mainLabel;
+};
+
+typedef std::unique_ptr<PromptLabels> PromptLabelsPtr;
+
+enum Validity
+{
+    ONCE,
+    SESSION,
+    ALWAYS
+};
+
+class PromptAnswer
+{
+public:
+    PromptAnswer(bool isAccessAllowed, Validity validity);
+    PromptAnswer(int aPromptType, unsigned int buttonAns, bool checkAns);
+    bool isAccessAllowed() const;
+    Validity getValidity() const;
+
+private:
+    bool m_isAccessAllowed;
+    Validity m_validity;
+};
+
+class PromptModel
+{
+  public:
+    static PromptLabels* getOneShotModel(const std::string& resourceId);
+    static PromptLabels* getSessionModel(const std::string& resourceId);
+    static PromptLabels* getBlanketModel(const std::string& resourceId);
+
+    enum PromptType
+    {
+        PROMPT_ONESHOT,
+        PROMPT_SESSION,
+        PROMPT_BLANKET
+    };
+};
+
+} // Prompt
+
+#endif /* WRT_SRC_ACCESSCONTROL_ENGINE_PROMPT_MODEL_H_ */
diff --git a/ace/include/ace-dao-ro/TimedVerdict.h b/ace/include/ace-dao-ro/TimedVerdict.h
new file mode 100644 (file)
index 0000000..8f9be66
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       TimedVerdict.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_TIMEDVERDICT_H_
+#define ACCESS_CONTROL_DAO_TIMEDVERDICT_H_
+
+#include <ace-dao-ro/VerdictTypes.h>
+
+namespace AceDB{
+
+struct TimedVerdict
+{
+    VerdictTypes decision;
+    /*Below values are optional,its filled only when verdict depend on session*/
+    std::string session;
+    int subjectVerdictId;
+};
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/ValidityTypes.h b/ace/include/ace-dao-ro/ValidityTypes.h
new file mode 100644 (file)
index 0000000..1283cf1
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       ValidityTypes.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_VALIDITYTYPES_H_
+#define ACCESS_CONTROL_DAO_VALIDITYTYPES_H_
+
+namespace AceDB{
+
+enum class ValidityTypes
+{
+     ONCE,
+     SESSION,
+     ALWAYS,
+     UNWRITEABLE
+};
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/VerdictTypes.h b/ace/include/ace-dao-ro/VerdictTypes.h
new file mode 100644 (file)
index 0000000..8a312b5
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       VerdictTypes.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_VERDICTTYPES_H_
+#define ACCESS_CONTROL_DAO_VERDICTTYPES_H_
+
+namespace AceDB{
+
+enum class VerdictTypes
+{
+    VERDICT_PERMIT,
+    VERDICT_DENY,
+    //Verdict is innapplicable if policy evaluate to INAPPLICABLE,
+    //in this case WRT should decide what to do
+    VERDICT_INAPPLICABLE,
+    VERDICT_UNDETERMINED,
+    VERDICT_UNKNOWN,  //Verdict is unknown if Verdicts manager cannot find it
+    VERDICT_ASYNC,
+    VERDICT_ERROR
+};
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/common_dao_types.h b/ace/include/ace-dao-ro/common_dao_types.h
new file mode 100644 (file)
index 0000000..94b4c5e
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ * @file    common_dao_types.h
+ * @author  Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version 1.1
+ * @brief   This file contains the declaration of common data types for ace database.
+ */
+#ifndef ACE_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_
+#define ACE_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_
+
+#include <list>
+#include <dpl/optional_typedefs.h>
+#include <dpl/string.h>
+#include "AppTypes.h"
+
+typedef int WidgetHandle;
+typedef std::list<WidgetHandle> WidgetHandleList;
+
+namespace AceDB {
+
+enum {
+    INVALID_PLUGIN_HANDLE = -1
+};
+typedef int DbPluginHandle;
+
+enum CertificateSource {
+    SIGNATURE_DISTRIBUTOR = 0,
+    SIGNATURE_AUTHOR = 1
+};
+
+struct WidgetRegisterInfo {
+    AppTypes type;
+    DPL::OptionalString widget_id;
+    DPL::OptionalString authorName;
+    DPL::OptionalString version;
+    DPL::OptionalString shareHref;
+};
+
+typedef std::list <std::string> WidgetCertificateCNList;
+
+struct WidgetCertificateData {
+    enum Owner { AUTHOR, DISTRIBUTOR, UNKNOWN };
+    enum Type { ROOT, ENDENTITY };
+
+    Owner owner;
+    Type type;
+
+    int chainId;
+    std::string strMD5Fingerprint;
+    std::string strSHA1Fingerprint;
+    DPL::String strCommonName;
+
+    bool operator== (const WidgetCertificateData& certData) const {
+        return certData.chainId == chainId &&
+           certData.owner == owner &&
+           certData.strCommonName == strCommonName &&
+           certData.strMD5Fingerprint == strMD5Fingerprint &&
+           certData.strSHA1Fingerprint == strSHA1Fingerprint;
+    }
+};
+typedef std::list<WidgetCertificateData> WidgetCertificateDataList;
+
+typedef std::list<std::string> FingerPrintList;
+
+typedef std::list<std::string> CertificateChainList;
+class IWacSecurity {
+  public:
+    virtual ~IWacSecurity() {}
+    virtual const WidgetCertificateDataList& getCertificateList() const = 0;
+    virtual bool isRecognized() const = 0;
+    virtual bool isDistributorSigned() const = 0;
+    virtual bool isWacSigned() const = 0;
+    virtual void getCertificateChainList(CertificateChainList& list) const = 0;
+};
+
+} //namespace AceDB
+
+#endif /* ACE_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_ */
diff --git a/ace/include/ace-dao-rw/AceDAO.h b/ace/include/ace-dao-rw/AceDAO.h
new file mode 100644 (file)
index 0000000..bff6a51
--- /dev/null
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       AceDAO.h
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACEDAO_H_
+#define ACEDAO_H_
+
+#include <list>
+#include <map>
+#include <string>
+
+#include <dpl/optional_typedefs.h>
+#include <dpl/string.h>
+#include <ace-dao-ro/AceDAOReadOnly.h>
+#include <ace-dao-ro/ValidityTypes.h>
+#include <ace-dao-ro/AppTypes.h>
+
+namespace AceDB {
+/*
+ *
+ */
+class AceDAO : public AceDAOReadOnly
+{
+  public:
+
+    AceDAO() {}
+
+    // Policy Decisions
+    static void setPolicyResult(
+            const BaseAttributeSet &attributes,
+            const ExtendedPolicyResult &policyResult);
+
+    static void removePolicyResult(
+            const BaseAttributeSet &attributes);
+
+    // PromptDecision
+    static void setPromptDecision(
+            WidgetHandle widgetHandle,
+            int ruleId,
+            const boost::optional<DPL::String> &session,
+            PromptDecision decision);
+
+    static void clearPromptDecisions(void);
+
+    // reseting database
+    static void clearWidgetDevCapSettings(void);
+    static void clearDevCapSettings(void);
+    static void clearAllSettings(void);
+    static void resetDatabase(void);
+    // clears all databse information relevant to policy cache
+    static void clearPolicyCache(void);
+
+    // resource settings
+    static void setDevCapSetting(const std::string &resource,
+            PreferenceTypes preference);
+    static void removeDevCapSetting(const std::string &resource);
+
+    // user settings
+    static void setWidgetDevCapSetting(
+            const std::string &resource,
+            WidgetHandle handler,
+            PreferenceTypes);
+    static void removeWidgetDevCapSetting(
+            const std::string &resource,
+            WidgetHandle handler);
+
+    // resource and subject management
+    static int addResource(const std::string &request);
+
+    // utilities
+    static void addAttributes(const BaseAttributeSet &attributes);
+
+    // Setter for device capabilities that are requested in widgets config.
+    //
+    // Additional boolean flag means whether widget will always get
+    // (at launch) the SMACK permissions needed to use the device cap).
+    //
+    // 'permissions' is the map of device cap names and smack status for
+    // given widget handle.
+    static void setRequestedDevCaps(
+        WidgetHandle widgetHandle,
+        const RequestedDevCapsMap &permissions);
+
+    static void removeRequestedDevCaps(
+        WidgetHandle widgetHandle);
+
+    static void setAcceptedFeature(
+        WidgetHandle widgetHandle,
+        const FeatureNameVector &vector);
+
+    static void removeAcceptedFeature(WidgetHandle widgetHandle);
+
+    static void registerWidgetInfo(WidgetHandle handle,
+                                   const WidgetRegisterInfo& info,
+                                   const WidgetCertificateDataList& dataList);
+    static void unregisterWidgetInfo(WidgetHandle handle);
+
+};
+}
+#endif /* ACEDAO_H_ */
diff --git a/ace/include/ace/AbstractPolicyEnforcementPoint.h b/ace/include/ace/AbstractPolicyEnforcementPoint.h
new file mode 100644 (file)
index 0000000..9482915
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+#ifndef WRT_SRC_ACCESS_CONTROL_LOGIC_ABSTRACT_POLICY_ENFORCEMENT_POINTS_H
+#define WRT_SRC_ACCESS_CONTROL_LOGIC_ABSTRACT_POLICY_ENFORCEMENT_POINTS_H
+
+#include <ace/WRT_INTERFACE.h>
+#include <ace/PolicyResult.h>
+#ifdef DBUS_CONNECTION
+#include <dpl/event/inter_context_delegate.h>
+#endif
+class AbstractPolicyEnforcementPoint
+{
+  public:
+#ifdef DBUS_CONNECTION
+    typedef DPL::Event::ICDelegate<PolicyResult> ResponseReceiver;
+#endif
+    virtual ExtendedPolicyResult check(Request &request) = 0;
+};
+
+#endif /* WRT_SRC_ACCESS_CONTROL_LOGIC_ABSTRACT_POLICY_ENFORCEMENT_POINTS_H */
diff --git a/ace/include/ace/AbstractPolicyInformationPoint.h b/ace/include/ace/AbstractPolicyInformationPoint.h
new file mode 100644 (file)
index 0000000..e8d95ed
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+class AbstractPolicyInformationPoint
+{
+  public:
+    virtual ~AbstractPolicyInformationPoint() {}
+};
diff --git a/ace/include/ace/AbstractTreeElement.h b/ace/include/ace/AbstractTreeElement.h
new file mode 100644 (file)
index 0000000..ffe2e89
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : AbstractTreeElement.h
+//  @ Date : 2009-05-25
+//  @ Author : Samsung
+//
+//
+#if !defined(_ABSTRACTTREEELEMENT_H)
+#define _ABSTRACTTREEELEMENT_H
+
+#include <list>
+#include "Effect.h"
+#include <iostream>
+
+class AbstractTreeElement
+{
+  public:
+
+    virtual ~AbstractTreeElement()
+    {
+    }
+
+    virtual void printData() = 0;
+  protected:
+};
+
+#endif  //_ABSTRACTTREEELEMENT_H
diff --git a/ace/include/ace/AsyncVerdictResultListener.h b/ace/include/ace/AsyncVerdictResultListener.h
new file mode 100644 (file)
index 0000000..47ef573
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#ifndef _ASYNCVERDICT_H
+#define _ASYNCVERDICT_H
+
+#include <ace/Verdict.h>
+#include <ace/WRT_INTERFACE.h>
+#include <ace/Request.h>
+
+class AsyncVerdictResultListener
+{
+  public:
+    virtual void onVerdict(const Verdict &verdict,
+            const Request *request) = 0;
+    virtual ~AsyncVerdictResultListener()
+    {
+    }
+};
+
+#endif
diff --git a/ace/include/ace/Attribute.h b/ace/include/ace/Attribute.h
new file mode 100644 (file)
index 0000000..e1a62b4
--- /dev/null
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Attribute.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_ATTRIBUTE_H)
+#define _ATTRIBUTE_H
+
+#include <string>
+#include <iostream>
+#include <set>
+#include <list>
+
+#include <ace-dao-ro/BaseAttribute.h>
+
+class Attribute : public AceDB::BaseAttribute
+{
+  public:
+    /**
+     * Types of match functions
+     */
+    enum class Match { Equal, Glob, Regexp, Error };
+    /**
+     * Types of attribute value modifiers
+     */
+    enum class Modifier { Non, Scheme, Authority, SchemeAuthority, Host, Path };
+    /**
+     * Possible match results
+     */
+    enum class MatchResult { MRUndetermined = -1, MRFalse = 0, MRTrue = 1};
+
+  public:
+
+    /**
+     * New attribute constructor
+     * @param name name of the new attribute
+     * @param matchFunction match function used in the attribute
+     * @param type attribute type
+     */
+    Attribute(const std::string *name,
+              const Match matchFunction,
+              const Type type);
+
+
+    /**
+     * Constructor used to create default attribute ( used for unit tests )
+     * @param nm name of the default attribute
+     */
+    Attribute(const std::string& nm) :
+        matchFunction(Match::Error),
+        modifierFunction(Modifier::Non)
+    {
+        m_name = nm;
+        m_typeId = Type::Subject;
+        m_undetermindState = false;
+    }
+
+    /**
+     * Destructor
+     */
+    virtual ~Attribute();
+
+    std::list<std::string> * getValue() const
+    {
+        return AceDB::BaseAttribute::getValue();
+    }
+    Match getMatchFunction() const
+    {
+        return matchFunction;
+    }
+
+    /*  --- Setters --- */
+    void addValue (const std::string *value);
+
+    MatchResult  matchAttributes(const BaseAttribute *) const;
+
+    /**
+     * Operator used in for attribute set,used to distinguished only attribute names
+     * It cannot take attribute type into consideration
+     */
+    bool operator< (const Attribute & obj) const
+    {
+        int result = this->m_name.compare(*obj.getName());
+        if (result == 0) { //If names are equal check attribute types
+            if (this->m_typeId < obj.getType()) {
+                result = -1;
+            } else if (this->m_typeId > obj.getType()) {
+                result = 1;
+            }
+        }
+        //If result is negative that means that 'this' was '<' than obj
+        return result < 0;
+    }
+
+     /** Checks if object type is equal to argument */
+    bool instanceOf(Type type_)
+    {
+        return type_ == m_typeId;
+    }
+
+    friend std::ostream & operator<<(std::ostream & out,
+                                     const Attribute & attr);
+
+  protected:
+
+    bool searchAndCut(const char *);
+
+    /*
+     *  URI definition from rfc2396
+     *
+     *  <scheme>://<authority><path>?<query>
+     *  Each of the components may be absent, apart from the scheme.
+     *  Host is a part of authority as in definition below:
+     *
+     *  authority     = server | reg_name
+     *  server        = [ [ userinfo "@" ] hostport ]
+     *  <userinfo>@<host>:<port>
+     *
+     *  Extract from rfc2396
+     *  The authority component is preceded by a double slash "//" and is
+     *  terminated by the next slash "/", question-mark "?", or by the end of
+     *  the URI.  Within the authority component, the characters ";", ":",
+     * "@", "?", and "/" are reserved.
+     *
+     *  Modifiers should return pointer to empty string if given part of string was empty.
+     *  Modifiers should return NULL if the string to be modified was not an URI.
+     */
+    std::string * uriScheme(const std::string *) const;
+    std::string * uriAuthority(const std::string *) const;
+    std::string * uriSchemeAuthority(const std::string *) const;
+    std::string * uriHost(const std::string *) const;
+    std::string * uriPath(const std::string *) const;
+    std::string * applyModifierFunction(const std::string * val) const;
+
+    bool parse(const std::string *input,
+            std::string *part) const;
+    bool find_error(const std::string *part) const;
+
+    bool checkScheme(const std::string *scheme) const;
+    bool checkAuthority(const std::string *scheme) const;
+    std::string * getHost(const std::string *scheme) const;
+    bool checkPath(const std::string *scheme) const;
+
+    bool isSchemeAllowedCharacter(int c) const;
+    bool isSegmentAllowedCharacter(int c) const;
+    bool isUserInfoAllowedString(const std::string *str) const;
+    bool isHostAllowedString(const std::string *str) const;
+    bool isHostNameAllowedString(const std::string * str) const;
+    bool isIPv4AllowedString(const std::string * str) const;
+    bool isDomainLabelAllowedString(const char * data,
+                                    int lenght) const;
+    bool isTopLabelAllowedString(const char* data,
+                                 int lenght) const;
+
+    bool isUnreserved(int c) const;
+    bool isAlphanum(int c) const;
+    bool isEscaped(const char esc[3]) const;
+    bool isHex(int c) const;
+
+    MatchResult lists_comparator(
+        const std::list<std::string> *first,
+        const std::list<std::string> *second,
+        MatchResult (*comparator)(const std::string *,
+                                  const std::string *)) const;
+
+    /**
+     *  Map used to check if character is a 'mark'
+     */
+    static const bool mark[256];
+    /**
+     *  Map used to check if character is a 'digit'
+     *
+     */
+    static const bool digit[256];
+    /**
+     * Map used to check if character is an 'alphanumeric' value
+     *
+     */
+    static const bool alpha[256];
+
+  protected:
+    Match matchFunction;
+    Modifier modifierFunction;
+};
+
+typedef AceDB::BaseAttributeSet AttributeSet;
+
+//TODO remove later or ifdef debug methods
+void printAttributes(const AttributeSet& attrs);
+void printAttributes(const std::list<Attribute> & attrs);
+
+#endif  //_ATTRIBUTE_H
diff --git a/ace/include/ace/Combiner.h b/ace/include/ace/Combiner.h
new file mode 100644 (file)
index 0000000..784dcea
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Combiner.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_COMBINER_H)
+#define _COMBINER_H
+
+#include <set>
+
+#include <ace/Attribute.h>
+#include <ace/TreeNode.h>
+
+class Combiner
+{
+  protected:
+
+    const AttributeSet * attrSet;
+
+  public:
+
+    virtual ExtendedEffect combineRules(const TreeNode * rule) = 0;
+    virtual ExtendedEffect combinePolicies(const TreeNode * policy) = 0;
+
+    const AttributeSet * getAttributeSet() const
+    {
+        return this->attrSet;
+    }
+    void setAttributeSet(const AttributeSet * attrSet)
+    {
+        this->attrSet = attrSet;
+    }
+    virtual ~Combiner()
+    {
+    }                       //attrSet is deleted elsewhere
+};
+
+#endif  //_COMBINER_H
diff --git a/ace/include/ace/CombinerImpl.h b/ace/include/ace/CombinerImpl.h
new file mode 100644 (file)
index 0000000..d7c2e21
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : CombinerImpl.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _COMBINER_IMPL_H
+#define _COMBINER_IMPL_H
+
+#include <list>
+#include <dpl/log/log.h>
+
+#include "Combiner.h"
+#include "Effect.h"
+#include "Policy.h"
+#include "Subject.h"
+
+class CombinerImpl : public Combiner
+{
+  public:
+
+    virtual ExtendedEffect combineRules(const TreeNode * rule);
+    virtual ExtendedEffect combinePolicies(const TreeNode * policy);
+
+    virtual ~CombinerImpl()
+    {
+    }
+
+  protected:
+
+    bool checkIfTargetMatches(const std::list<const Subject *> * subjectsSet,
+            bool &isUndetermined);
+
+    ExtendedEffect combine(Policy::CombineAlgorithm algorithm,
+            ExtendedEffectList &effects);
+
+    ExtendedEffect denyOverrides(const ExtendedEffectList &effects);
+    ExtendedEffect permitOverrides(const ExtendedEffectList &effects);
+    ExtendedEffect firstApplicable(const ExtendedEffectList &effects);
+    ExtendedEffect firstMatchingTarget(const ExtendedEffectList &effects);
+
+    std::list<int> * convertEffectsToInts(const std::list<Effect> * effects);
+    Effect convertIntToEffect(int intEffect);
+
+    void showEffectList(ExtendedEffectList & effects)
+    {
+        ExtendedEffectList::iterator it = effects.begin();
+        for (; it != effects.end(); ++it) {
+            LogDebug(toString(*it));
+        }
+    }
+
+  private:
+    bool isError(const ExtendedEffectList &effects);
+};
+
+#endif  //_COMBINERIMPL_H
diff --git a/ace/include/ace/Condition.h b/ace/include/ace/Condition.h
new file mode 100644 (file)
index 0000000..918c1fe
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+// File:   Condition.h
+// Author: notroot
+//
+// Created on June 3, 2009, 9:00 AM
+//
+#ifndef _CONDITION_H
+#define _CONDITION_H
+
+#include <list>
+#include <set>
+#include <iostream>
+#include <dpl/foreach.h>
+
+#include "Attribute.h"
+#include "Effect.h"
+#include "TreeNode.h"
+
+class Condition
+{
+  public:
+    enum CombineType
+    {
+        AND, OR
+    };
+
+    void addCondition(const Condition & condition)
+    {
+        this->conditions.push_back(condition);
+    }
+
+    void addAttribute(const Attribute & attribute)
+    {
+        this->attributes.push_back(attribute);
+    }
+
+    void setCombineType(CombineType type)
+    {
+        this->combineType = type;
+    }
+
+    Condition() : combineType(AND),
+        parent(NULL)
+    {
+    }
+
+    Condition(CombineType type) : combineType(type),
+        parent(NULL)
+    {
+    }
+
+    virtual ~Condition()
+    {
+    }
+
+    Condition * getParent()
+    {
+        return this->parent;
+    }
+
+    void setParent(Condition * condition)
+    {
+        this->parent = condition;
+    }
+
+    Attribute::MatchResult evaluateCondition(
+            const AttributeSet * attrSet) const;
+
+    friend std::ostream & operator<<(std::ostream & out,
+            Condition & condition)
+    {
+        FOREACH (it, condition.attributes)
+        {
+            out << *it;
+        }
+        return out;
+    }
+    //[CR] change function name
+    void getAttributes(AttributeSet * attrSet);
+
+  private:
+    Attribute::MatchResult evaluateChildConditions(
+            const AttributeSet * attrSet,
+            bool &isFinalMatch,
+            bool & undefinedMatchFound) const;
+
+    Attribute::MatchResult evaluateAttributes(
+            const AttributeSet * attrSet,
+            bool& isFinalMatch,
+            bool & undefinedMatchFound) const;
+
+    // KW     Attribute::MatchResult performANDalgorithm(const std::set<Attribute> * attributes) const;
+
+    // KW     Attribute::MatchResult performORalgorithm(const std::set<Attribute> * attributes) const;
+
+    bool isEmpty() const
+    {
+        return attributes.empty() && conditions.empty();
+    }
+
+    bool isAndCondition() const
+    {
+        return combineType == AND;
+    }
+
+    bool isOrCondition() const
+    {
+        return combineType == OR;
+    }
+
+    std::list<Condition> conditions;
+    CombineType combineType;
+    std::list<Attribute> attributes;
+    Condition *parent;
+};
+
+#endif    /* _CONDITION_H */
+
diff --git a/ace/include/ace/ConfigurationManager.h b/ace/include/ace/ConfigurationManager.h
new file mode 100644 (file)
index 0000000..627f9da
--- /dev/null
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#ifndef _CONFIGURATIONMANAGER_H_
+#define _CONFIGURATIONMANAGER_H_
+
+#include <list>
+#include <string.h>
+#include <string>
+#include "Constants.h"
+#include <iostream>
+#include <dpl/log/log.h>
+
+enum class PolicyType {
+    WAC2_0,
+    Tizen
+};
+
+#define POLICY_NAME_WAC2_0                  "WAC2.0"
+#define POLICY_NAME_TIZEN                   "Tizen"
+#define POLICY_WIDGET_TYPE_ATTRIBUTE_NAME   "WrtSecurity.WidgetPolicyType"
+
+#pragma message "ATTR_ACTIVE_POLICY BAD_CAST, PARSER_ERROR, PARSER_SUCCESS\
+ macros are DEPRECATED"
+#define ATTR_ACTIVE_POLICY BAD_CAST("active") // !! DEPRECATED !!
+#define PARSER_ERROR     1 // !! DEPRECATED !!
+#define PARSER_SUCCESS   0 // !! DEPRECATED !!
+
+class ConfigurationManager
+{
+  public:
+    // !! DEPRECATED !!
+    enum ConfigurationManagerResult
+    {
+        CM_OPERATION_SUCCESS = 0,
+        CM_GENERAL_ERROR = -1,
+        CM_FILE_EXISTS = -2,
+        CM_REMOVE_ERROR = -3,
+        CM_REMOVE_CURRENT = -4,
+        CM_REMOVE_NOT_EXISTING = -5
+    };
+
+    // !! DEPRECATED !!
+    std::string getCurrentPolicyFile(void) const;
+    std::string getFullPathToCurrentPolicyFile(void) const;
+    std::string getFullPathToCurrentPolicyXMLSchema(void) const;
+    int addPolicyFile(const std::string & filePath);
+    int removePolicyFile(const std::string& fileName);
+    int changeCurrentPolicyFile(const std::string& filePath);
+    std::string extractFilename(const std::string& path) const;
+
+    /**
+     * ACE policy file path getter
+     * @return Full path to policy file
+     */
+    std::string getFullPathToPolicyFile(PolicyType policy) const;
+
+    /**
+     * ACE policy dtd file path getter
+     * @return Full path to ACE current policy file
+     */
+    std::string getFullPathToPolicyXMLSchema(void) const;
+
+    /**
+     * ACE policy storage path getter
+     * @return Full path to ACE policy file storage
+     */
+    std::string getCscStoragePath(void) const;
+
+   /**
+     * ACE policy storage path getter
+     * @return Full path to ACE policy file storage
+     */
+    std::string getStoragePath(void) const;
+
+    /**
+     * Method to obtain instance of configuration manager
+     * @return retuns pointer to configuration manager or NULL in case of error
+     */
+    static ConfigurationManager * getInstance()
+    {
+        if (!instance) {
+            instance = new ConfigurationManager();
+        }
+        return instance;
+    }
+
+  protected:
+
+    // !! DEPRECATED !!
+    int parse(const std::string&);
+    bool copyFile(FILE*, FILE*, int lenght = 1024) const;
+    bool checkIfFileExistst(const std::string&) const;
+    const std::list<std::string> & getPolicyFiles() const;
+    const std::string & getConfigFile() const;
+
+    ConfigurationManager()
+    {
+    }
+    virtual ~ConfigurationManager()
+    {
+    }
+
+private:
+
+    static ConfigurationManager * instance;
+};
+
+#endif
+
diff --git a/ace/include/ace/Constants.h b/ace/include/ace/Constants.h
new file mode 100644 (file)
index 0000000..346bb0e
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        Constants.h
+ * @author      Piotr Fatyga (p.fatyga@samsung.com)
+ * @version     0.1
+ * @brief
+ */
+
+#ifndef _CONSTANTS_H
+#define _CONSTANTS_H
+
+#define ACE_MAIN_STORAGE "/usr/etc/ace"
+#define ACE_CSC_STORAGE "/opt/system/csc-default/usr/web"
+#define ACE_WAC_POLICY_FILE_NAME "/WAC2.0Policy.xml"
+#define ACE_TIZEN_POLICY_FILE_NAME "/TizenPolicy.xml"
+#define ACE_DTD_LOCATION ACE_MAIN_STORAGE "/bondixml.dtd"
+
+// !! DEPRECATED !!
+#pragma message "ACE_CONFIGURATION_PATH, ACE_CONFIGURATION_DTD \
+ macros are DEPRECATED"
+#define ACE_CONFIGURATION_PATH ACE_MAIN_STORAGE "/config.xml"
+#define ACE_CONFIGURATION_DTD ACE_MAIN_STORAGE "/config.dtd"
+
+/////////////////FOR GUI//////////////////////
+
+#define MYSTERIOUS_BITMAP "/usr/apps/org.tizen.policy/d.png"
+#define MYSTERIOUS_BITMAP2 "/usr/apps/org.tizen.policy/file.png"
+
+///////////////////FOR TESTS//////////////////////////
+
+#define COMBINER_TEST "/usr/etc/ace/CMTest/com_general-test.xml"
+#define CONFIGURATION_MGR_TEST_PATH "/usr/etc/ace/CMTest/"
+#define CONFIGURATION_MGR_TEST_CONFIG ACE_MAIN_STORAGE "/CMTest/pms_config.xml"
+#define CONFIGURATION_MGR_TEST_POLICY_STORAGE ACE_MAIN_STORAGE "/CMTest/active"
+#define CONFIGURATION_MGR_TEST_POLICY_STORAGE_MOVED ACE_MAIN_STORAGE \
+    "/CMTest/activeMoved"
+#define CONFIGURATION_MGR_TEST_POLICY CONFIGURATION_MGR_TEST_POLICY_STORAGE \
+    "/pms_general-test.xml"
+#define POLICIES_TO_SIGN_DIR ACE_MAIN_STORAGE "/SignerTests/"
+
+#define OUTPUT_DIR ACE_MAIN_STORAGE "/SignerTests/signedPolicies/"
+#define PRIVATE_KEY_DIR ACE_MAIN_STORAGE "/SignerTests/PrvKey/"
+#define X509_DATA_BASE_DIR ACE_MAIN_STORAGE "/SignerTests/X509Data/"
+
+#endif    /* _CONSTANTS_H */
+
diff --git a/ace/include/ace/Effect.h b/ace/include/ace/Effect.h
new file mode 100644 (file)
index 0000000..c771c15
--- /dev/null
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Effect.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _EFFECT_H_
+#define _EFFECT_H_
+
+#include <list>
+
+typedef int RuleId;
+
+enum Effect
+{
+    Deny =0,
+    Undetermined=1,    // jk mb added this enum, so the ones below are inceremented!!!!!!!
+    PromptOneShot =2,
+    PromptSession =3,
+    PromptBlanket =4,
+    Permit =5,
+    Inapplicable =6,
+    NotMatchingTarget=7,
+    Error=8,
+};
+
+struct ExtendedEffect {
+public:
+    ExtendedEffect(Effect effect = Error, RuleId ruleId = -1)
+      : m_effect(effect)
+      , m_ruleId(ruleId)
+    {}
+
+    ExtendedEffect(const ExtendedEffect &second)
+      : m_effect(second.m_effect)
+      , m_ruleId(second.m_ruleId)
+    {}
+
+    ExtendedEffect& operator=(const ExtendedEffect &second) {
+        m_effect = second.m_effect;
+        m_ruleId = second.m_ruleId;
+        return *this;
+    }
+
+    Effect getEffect() const { return m_effect; }
+
+    RuleId getRuleId() const { return m_ruleId; }
+
+private:
+    Effect m_effect;
+    RuleId m_ruleId;
+};
+
+typedef std::list<ExtendedEffect> ExtendedEffectList;
+
+inline const char *toString(const ExtendedEffect &effect)
+{
+    const char * temp = "";
+
+    switch (effect.getEffect()) {
+    case Deny:
+        temp = "Deny";
+        break;
+    case Undetermined:
+        temp = "Undetermined";
+        break;
+    case PromptOneShot:
+        temp = "PromptOneShot";
+        break;
+    case PromptSession:
+        temp = "PromptSession";
+        break;
+    case PromptBlanket:
+        temp = "PromptBlanket";
+        break;
+    case Permit:
+        temp = "Permit";
+        break;
+    case Inapplicable:
+        temp = "Inapplicable";
+        break;
+    case NotMatchingTarget:
+        temp = "NotMatchingTarget";
+        break;
+    case Error:
+        temp = "Error";
+        break;
+    default:;
+    }
+    return temp;
+}
+
+#endif  //_EFFECT_H_
diff --git a/ace/include/ace/PermissionTriple.h b/ace/include/ace/PermissionTriple.h
new file mode 100644 (file)
index 0000000..fcb7e47
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PermissionTriple.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_PERMISSION_TRIPLE_H)
+#define _PERMISSION_TRIPLE_H
+
+#include <string>
+#include <list>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace-dao-ro/BasePermission.h>
+
+typedef AceDB::BasePermission PermissionTriple;
+typedef AceDB::BasePermissionList PermissionList;
+
+struct GeneralSetting
+{
+    GeneralSetting(const std::string& resourceName,
+            AceDB::PreferenceTypes accessAllowed) : generalSettingName(resourceName),
+        access(accessAllowed)
+    {
+    }
+    std::string generalSettingName;
+    AceDB::PreferenceTypes access;
+};
+
+#endif  //_PERMISSION_TRIPLE_H
diff --git a/ace/include/ace/Policy.h b/ace/include/ace/Policy.h
new file mode 100644 (file)
index 0000000..2c43bd5
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Policy.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_POLICY_H)
+#define _POLICY_H
+
+#include <list>
+
+#include <ace/AbstractTreeElement.h>
+#include <ace/Effect.h>
+#include <ace/Attribute.h>
+#include <ace/Subject.h>
+#include <iostream>
+#include <dpl/noncopyable.h>
+
+class Policy : public AbstractTreeElement,
+    DPL::Noncopyable
+{
+  public:
+    enum CombineAlgorithm { DenyOverride, PermitOverride, FirstApplicable,
+                            FirstTargetMatching };
+
+    Policy()
+    {
+        combineAlgorithm = DenyOverride;
+        subjects = new std::list<const Subject *>();
+    }
+
+    CombineAlgorithm getCombineAlgorithm() const
+    {
+        return this->combineAlgorithm;
+    }
+
+    void setCombineAlgorithm(CombineAlgorithm algorithm)
+    {
+        this->combineAlgorithm = algorithm;
+    }
+
+    const std::list<const Subject *> * getSubjects() const
+    {
+        return this->subjects;
+    }
+
+    void addSubject(const Subject * subject)
+    {
+        if (this->subjects == NULL) {
+            return;
+        }
+        this->subjects->push_back(subject);
+    }
+
+    virtual ~Policy();
+
+    void printData();
+
+    std::string printCombineAlgorithm(CombineAlgorithm algorithm);
+
+  private:
+    std::list<const Subject *> *subjects;
+    CombineAlgorithm combineAlgorithm;
+};
+
+const char * toString(Policy::CombineAlgorithm algorithm);
+
+#endif  //_POLICY_H
diff --git a/ace/include/ace/PolicyEffect.h b/ace/include/ace/PolicyEffect.h
new file mode 100644 (file)
index 0000000..43c79d7
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    PolicyEffect.h
+ * @author  B.Grzelewski (b.grzelewski@samsung.com)
+ * @version 1.0
+ * @brief   This file contains the declaration of PolicyEffect type.
+ */
+#ifndef _SRC_ACCESS_CONTROL_COMMON_POLICY_EFFECT_H_
+#define _SRC_ACCESS_CONTROL_COMMON_POLICY_EFFECT_H_
+
+enum class PolicyEffect {
+    DENY = 0,
+    PERMIT,
+    PROMPT_ONESHOT,
+    PROMPT_SESSION,
+    PROMPT_BLANKET
+};
+
+inline static std::ostream & operator<<(std::ostream& stream,
+                                        PolicyEffect effect)
+{
+    switch (effect) {
+        case PolicyEffect::DENY:           stream << "DENY"; break;
+        case PolicyEffect::PERMIT:         stream << "PERMIT"; break;
+        case PolicyEffect::PROMPT_ONESHOT: stream << "PROMPT_ONESHOT"; break;
+        case PolicyEffect::PROMPT_SESSION: stream << "PROMPT_SESSION"; break;
+        case PolicyEffect::PROMPT_BLANKET: stream << "PROMPT_BLANKET"; break;
+        default: Assert(false && "Invalid PolicyEffect constant");
+    }
+    return stream;
+}
+
+#endif // _SRC_ACCESS_CONTROL_COMMON_POLICY_EFFECT_H_
diff --git a/ace/include/ace/PolicyEnforcementPoint.h b/ace/include/ace/PolicyEnforcementPoint.h
new file mode 100644 (file)
index 0000000..79e8e5b
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This class simply redirects the access requests to access control engine.
+ * The aim is to hide access control engine specific details from WRT modules.
+ * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
+ * WRT specific and other information during the decision making.
+ *
+ * @file    security_logic.h
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @brief   Implementation file for security logic
+ */
+#ifndef POLICY_ENFORCEMENT_POINT_H
+#define POLICY_ENFORCEMENT_POINT_H
+
+#include <memory>
+#include <string>
+#include <map>
+
+//#include <glib/gthread.h>
+//#include <glib/gerror.h>
+//#include <glib.h>
+
+#ifdef DBUS_CONNECTION
+#include <dpl/event/inter_context_delegate.h>
+#include <dpl/event/property.h>
+#endif
+
+#include <ace/AbstractPolicyEnforcementPoint.h>
+#include <ace/PolicyResult.h>
+
+// Forwards
+class IWebRuntime;
+class IResourceInformation;
+class IOperationSystem;
+class PolicyEvaluator;
+class PolicyInformationPoint;
+class Request;
+
+class PolicyEnforcementPoint : public AbstractPolicyEnforcementPoint
+{
+  public:
+    OptionalExtendedPolicyResult checkFromCache(Request &request);
+    ExtendedPolicyResult check(Request &request);
+    OptionalExtendedPolicyResult check(Request &request,
+                               bool fromCacheOnly);
+
+    virtual ~PolicyEnforcementPoint();
+
+    class PEPException
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, AlreadyInitialized)
+    };
+
+    /**
+     * This function take ownership of objects pass in call.
+     * Object will be deleted after call Deinitialize function.
+     */
+    void initialize(IWebRuntime *wrt,
+                    IResourceInformation *resource,
+                    IOperationSystem *operation);
+    void terminate();
+
+    void updatePolicy(const std::string &policy);
+    void updatePolicy();
+
+    PolicyEvaluator *getPdp() const { return this->m_pdp; }
+    PolicyInformationPoint *getPip() const { return this->m_pip; }
+
+  protected:
+    PolicyEnforcementPoint();
+    friend class SecurityLogic;
+  private: // private data
+    IWebRuntime                     *m_wrt;
+    IResourceInformation            *m_res;
+    IOperationSystem                *m_sys;
+    PolicyEvaluator                 *m_pdp;
+    PolicyInformationPoint          *m_pip;
+};
+
+#endif // POLICY_ENFORCEMENT_POINT_H
diff --git a/ace/include/ace/PolicyEvaluator.h b/ace/include/ace/PolicyEvaluator.h
new file mode 100644 (file)
index 0000000..786b6a9
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PolicyEvaluator.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _POLICY_EVALUATOR_H
+#define _POLICY_EVALUATOR_H
+
+#include <memory>
+#include <set>
+#include <string>
+
+#ifdef DBUS_CONNECTION
+#include <dpl/event/event_listener.h>
+#endif
+#include <dpl/log/log.h>
+#include <dpl/noncopyable.h>
+
+#include <ace/AsyncVerdictResultListener.h>
+#include <ace/Attribute.h>
+#include <ace/ConfigurationManager.h>
+#include <ace/Constants.h>
+#include <ace/Effect.h>
+#include <ace/Policy.h>
+#include <ace/PolicyInformationPoint.h>
+#include <ace/PolicyResult.h>
+#include <ace/Request.h>
+#include <ace/Subject.h>
+#include <ace/Verdict.h>
+#include <ace/UserDecision.h>
+#include <ace/CombinerImpl.h>
+
+
+class PolicyEvaluator : DPL::Noncopyable
+{
+  protected:
+
+    /**
+     * Internal method used to initiate policy evaluation. Called after attribute set has been fetched
+     * by PIP.
+     * @param root root of the policies tree to be evaluated
+     */
+    virtual ExtendedEffect evaluatePolicies(const TreeNode * root);
+
+    // !! DEPRECATED !!
+    enum updateErrors
+    {
+        POLICY_PARSING_SUCCESS = 0,
+        POLICY_FILE_ERROR = 1,
+        PARSER_CREATION_ERROR,
+        POLICY_PARSING_ERROR
+    };
+  private:
+    AttributeSet m_attributeSet;
+
+    TreeNode *m_uniform_policy, *m_wac_policy, *m_tizen_policy;
+    std::string m_currentPolicyFile;
+    PolicyType m_policy_to_use;
+
+    Combiner * m_combiner;
+    AsyncVerdictResultListener * m_verdictListener;
+    PolicyInformationPoint * m_pip;
+
+    /**
+     * @return current policy Tree acc. to m_policy_to_use
+     */
+    TreeNode * getCurrentPolicyTree();
+
+    /**
+     * Method used to extract attributes from subtree defined by PolicySet
+     * @param root original TreeStructure root node
+     * @param newRoot copy of TreeStructure containing only policies that matches current request
+     *
+     */
+    void extractAttributesFromSubtree(const TreeNode *root);
+
+    /**
+     * Method used to extract attributes from Tree Structure
+     * @return pointer to set of attributes needed to evaluate current request
+     * @return if extraction has been successful
+     * TODO return reducte tree structure
+     * TODO change comments
+     */
+    bool extractAttributesFromRules(const TreeNode *);
+
+    /**
+     * Extracts attributes from target of a given policy that are required to be fetched by PIP
+     */
+    void extractTargetAttributes(const Policy *policy);
+    bool extractAttributes(TreeNode*);
+
+    OptionalExtendedPolicyResult getPolicyForRequestInternal(bool fromCacheOnly);
+    PolicyResult effectToPolicyResult(Effect effect);
+
+    /**
+     * Return safe policy tree in case of error with loading policy from file
+     */
+    TreeNode * getDefaultSafePolicyTree(void);
+
+  public:
+    PolicyEvaluator(PolicyInformationPoint * pip);
+
+    bool extractAttributesTest()
+    {
+        m_attributeSet.clear();
+        if (!extractAttributes(m_uniform_policy)) {
+            LogInfo("Warnign attribute set cannot be extracted. Returning Deny");
+            return true;
+        }
+
+        return extractAttributes(m_uniform_policy);
+    }
+
+    AttributeSet * getAttributeSet()
+    {
+        return &m_attributeSet;
+    }
+
+    virtual bool initPDP();
+    virtual ~PolicyEvaluator();
+    virtual ExtendedPolicyResult getPolicyForRequest(const Request &request);
+    virtual OptionalExtendedPolicyResult getPolicyForRequestFromCache(
+        const Request &request);
+    virtual OptionalExtendedPolicyResult getPolicyForRequest(const Request &request,
+                                                     bool fromCacheOnly);
+    bool fillAttributeWithPolicy();
+
+    virtual int updatePolicy(const char *);
+    // This function updates policy from well known locations
+    virtual void updatePolicy();
+
+    std::string getCurrentPolicy();
+};
+
+#endif  //_POLICYEVALUATOR_H
diff --git a/ace/include/ace/PolicyEvaluatorFactory.h b/ace/include/ace/PolicyEvaluatorFactory.h
new file mode 100644 (file)
index 0000000..73e36a1
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        AbstractObjectFactory.h
+ * @author      Piotr Fatyga (p.fatyga@samsung.com)
+ * @version     0.1
+ * @brief
+ */
+
+#ifndef _ABSTRACTOBJECTFACTORY_H
+#define    _ABSTRACTOBJECTFACTORY_H
+
+#include <ace/PolicyEvaluator.h>
+
+class AbstractPolicyEvaluatorFactory
+{
+  public:
+    virtual PolicyEvaluator * createPolicyEvaluator(PolicyInformationPoint *pip)
+    const = 0;
+};
+
+class PolicyEvaluatorFactory : public AbstractPolicyEvaluatorFactory
+{
+  public:
+    PolicyEvaluator * createPolicyEvaluator(PolicyInformationPoint *pip) const
+    {
+        return new PolicyEvaluator(pip);
+    }
+};
+
+#endif    /* _ABSTRACTOBJECTFACTORY_H */
+
diff --git a/ace/include/ace/PolicyInformationPoint.h b/ace/include/ace/PolicyInformationPoint.h
new file mode 100644 (file)
index 0000000..ccb9763
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PolicyInformationPoint.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _POLICY_INFORMATION_POINT_H
+#define _POLICY_INFORMATION_POINT_H
+
+#include <set>
+
+#include <ace/Attribute.h>
+#include <ace/Request.h>
+#include <ace/WRT_INTERFACE.h>
+#include <ace-dao-ro/BaseAttribute.h>
+#include <dpl/noncopyable.h>
+
+typedef int PipResponse;
+
+class PolicyInformationPoint : public DPL::Noncopyable
+{
+  private:
+
+    /** queries for interfaces*/
+    std::list<ATTRIBUTE> resourceAttributesQuery;
+    std::list<ATTRIBUTE> environmentAttributesQuery;
+    std::list<ATTRIBUTE> subjectAttributesQuery;
+    std::list<ATTRIBUTE> functionParamAttributesQuery;
+    std::list<ATTRIBUTE> widgetParamAttributesQuery;
+
+    /** create queries */
+    void createQueries(AttributeSet* attributes);
+
+    IWebRuntime* wrtInterface;
+    IResourceInformation* resourceInformation;
+    IOperationSystem* operationSystem;
+
+  public:
+    static const int ERROR_SHIFT_RESOURCE = 3;
+    static const int ERROR_SHIFT_OS = 6;
+    static const int ERROR_SHIFT_FP = 9;
+
+    /** Mask used to identify PIP error */
+    enum ResponseTypeMask
+    {
+        SUCCESS               = 0,
+        /* WebRuntime Error */
+        WRT_UNKNOWN_SUBJECT   = 1 << 0,
+        WRT_UNKNOWN_ATTRIBUTE = 1 << 1,
+        WRT_INTERNAL_ERROR    = 1 << 2,
+        /* Resource Information Storage Error */
+        RIS_UNKNOWN_RESOURCE  = 1 << 3,
+        RIS_UNKNOWN_ATTRIBUTE = 1 << 4,
+        RIS_INTERNAL_ERROR    = 1 << 5,
+        /*Operating system */
+        OS_UNKNOWN_ATTRIBUTE  = 1 << 6,
+        OS_INTERNAL_ERROR     = 1 << 7
+    };
+
+    //TODO add checking values of attributes
+    /** gather attributes values from adequate interfaces */
+    virtual PipResponse getAttributesValues(const Request* request,
+            AttributeSet* attributes);
+    virtual ~PolicyInformationPoint();
+    PolicyInformationPoint(IWebRuntime *wrt,
+            IResourceInformation *resource,
+            IOperationSystem *system);
+    virtual void update(IWebRuntime *wrt,
+            IResourceInformation *resource,
+            IOperationSystem *system)
+    {
+        wrtInterface = wrt;
+        resourceInformation = resource;
+        operationSystem = system;
+    }
+    IWebRuntime * getWebRuntime()
+    {
+        return wrtInterface;
+    }
+};
+
+#endif  //_POLICY_INFORMATION_POINT_H
diff --git a/ace/include/ace/PolicyResult.h b/ace/include/ace/PolicyResult.h
new file mode 100644 (file)
index 0000000..a599013
--- /dev/null
@@ -0,0 +1,258 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+#ifndef _SRC_ACCESS_CONTROL_COMMON_POLICY_RESULT_H_
+#define _SRC_ACCESS_CONTROL_COMMON_POLICY_RESULT_H_
+
+#include <dpl/assert.h>
+#include <dpl/optional_typedefs.h>
+#include <boost/optional.hpp>
+#include <ace/PolicyEffect.h>
+
+typedef boost::optional<PolicyEffect> OptionalPolicyEffect;
+
+class PolicyDecision
+{
+public:
+    enum Value { NOT_APPLICABLE = -1 };
+
+    PolicyDecision(PolicyEffect effect)
+      : m_isPolicyEffect(true)
+      , m_effect(effect)
+    {}
+
+    PolicyDecision(const PolicyDecision &decision)
+      : m_isPolicyEffect(decision.m_isPolicyEffect)
+      , m_effect(decision.m_effect)
+    {}
+
+    PolicyDecision(Value)
+      : m_isPolicyEffect(false)
+    {}
+
+    bool operator==(const PolicyDecision &decision) const {
+        return (m_isPolicyEffect
+                 && decision.m_isPolicyEffect
+                 && m_effect == decision.m_effect)
+               || (!m_isPolicyEffect && !decision.m_isPolicyEffect);
+    }
+
+    bool operator==(Value) const {
+        return !m_isPolicyEffect;
+    }
+
+    bool operator!=(const PolicyDecision &decision) const {
+        return !(*this == decision);
+    }
+
+    bool operator!=(Value value) const {
+        return !(*this == value);
+    }
+
+    OptionalPolicyEffect getEffect() const
+    {
+        if (!m_isPolicyEffect) {
+            return OptionalPolicyEffect();
+        }
+        return OptionalPolicyEffect(m_effect);
+    }
+
+    std::ostream & toStream(std::ostream& stream) {
+        if (m_isPolicyEffect)
+            stream << m_effect;
+        else
+            stream << "NOT-APPLICABLE";
+        return stream;
+    }
+
+private:
+    bool m_isPolicyEffect;
+    PolicyEffect m_effect;
+};
+
+inline static bool operator==(PolicyEffect e, const PolicyDecision &d) {
+  return d.operator==(e);
+}
+
+inline static bool operator!=(PolicyEffect e, const PolicyDecision &d) {
+  return !(e == d);
+}
+
+inline static std::ostream & operator<<(std::ostream& stream,
+                                        PolicyDecision decision)
+{
+    return decision.toStream(stream);
+}
+
+class PolicyResult {
+public:
+    enum Value { UNDETERMINED = -2 };
+
+    // This constructor is required by dpl controller and by dpl optional
+    PolicyResult()
+      : m_isDecision(false)
+      , m_decision(PolicyDecision::Value::NOT_APPLICABLE) // don't care
+    {}
+
+    PolicyResult(PolicyEffect effect)
+      : m_isDecision(true)
+      , m_decision(effect)
+    {}
+
+    PolicyResult(const PolicyDecision &decision)
+      : m_isDecision(true)
+      , m_decision(decision)
+    {}
+
+    PolicyResult(const PolicyResult &result)
+      : m_isDecision(result.m_isDecision)
+      , m_decision(result.m_decision)
+    {}
+
+    PolicyResult(PolicyDecision::Value value)
+      : m_isDecision(true)
+      , m_decision(value)
+    {}
+
+    PolicyResult(Value)
+      : m_isDecision(false)
+      , m_decision(PolicyDecision::Value::NOT_APPLICABLE) // don't care
+    {}
+
+    bool operator==(const PolicyResult &result) const {
+          return (m_isDecision
+                && result.m_isDecision
+                && m_decision == result.m_decision)
+                || (!m_isDecision && !result.m_isDecision);
+    }
+
+    bool operator==(Value) const {
+        return !m_isDecision;
+    }
+
+    bool operator!=(const PolicyResult &result) const {
+        return !(*this == result);
+    }
+
+    bool operator!=(Value value) const {
+        return !(*this == value);
+    }
+
+    OptionalPolicyEffect getEffect() const
+    {
+        if (!m_isDecision) {
+            return OptionalPolicyEffect();
+        }
+        return m_decision.getEffect();
+    }
+
+    static int serialize(const PolicyResult &policyResult)
+    {
+        if (!policyResult.m_isDecision) {
+            return BD_UNDETERMINED;
+        } else if (policyResult.m_decision ==
+            PolicyDecision::Value::NOT_APPLICABLE)
+        {
+            return BD_NOT_APPLICABLE;
+        } else if (policyResult.m_decision == PolicyEffect::PROMPT_BLANKET) {
+            return BD_PROMPT_BLANKET;
+        } else if (policyResult.m_decision == PolicyEffect::PROMPT_SESSION) {
+            return BD_PROMPT_SESSION;
+        } else if (policyResult.m_decision == PolicyEffect::PROMPT_ONESHOT) {
+            return BD_PROMPT_ONESHOT;
+        } else if (policyResult.m_decision == PolicyEffect::PERMIT) {
+            return BD_PERMIT;
+        } else if (policyResult.m_decision == PolicyEffect::DENY) {
+            return BD_DENY;
+        }
+        Assert(false && "Unknown value of policyResult.");
+    }
+
+    static PolicyResult deserialize(int dec){
+        switch (dec) {
+            case BD_DENY:
+                return PolicyEffect::DENY;
+            case BD_PERMIT:
+                return PolicyEffect::PERMIT;
+            case BD_PROMPT_ONESHOT:
+                return PolicyEffect::PROMPT_ONESHOT;
+            case BD_PROMPT_SESSION:
+                return PolicyEffect::PROMPT_SESSION;
+            case BD_PROMPT_BLANKET:
+                return PolicyEffect::PROMPT_BLANKET;
+            case BD_NOT_APPLICABLE:
+                return PolicyDecision::Value::NOT_APPLICABLE;
+            case BD_UNDETERMINED:
+                return Value::UNDETERMINED;
+        }
+        Assert(false && "Broken database");
+    }
+
+    std::ostream & toStream(std::ostream& stream) {
+        if (m_isDecision)
+            stream << m_decision;
+        else
+            stream << "UNDETERMINED";
+        return stream;
+    }
+
+private:
+    static const int BD_UNDETERMINED = 6;
+    static const int BD_NOT_APPLICABLE = 5;
+    static const int BD_PROMPT_BLANKET = 4;
+    static const int BD_PROMPT_SESSION = 3;
+    static const int BD_PROMPT_ONESHOT = 2;
+    static const int BD_PERMIT = 1;
+    static const int BD_DENY = 0;
+
+    bool m_isDecision;
+    PolicyDecision m_decision;
+};
+
+inline static bool operator==(const PolicyDecision &d, const PolicyResult &r) {
+    return r == d;
+}
+
+inline static bool operator!=(const PolicyDecision &d, const PolicyResult &r) {
+    return !(d == r);
+}
+
+inline static bool operator==(const PolicyEffect &e, const PolicyResult &r) {
+    return e == r;
+}
+
+inline static bool operator!=(const PolicyEffect &e, const PolicyResult &r) {
+    return !(e == r);
+}
+
+inline static std::ostream & operator<<(std::ostream& stream,
+                                        PolicyResult result)
+{
+    return result.toStream(stream);
+}
+
+struct ExtendedPolicyResult {
+    ExtendedPolicyResult(const PolicyResult pr = PolicyEffect::DENY, int rule = -1)
+      : policyResult(pr)
+      , ruleId(rule)
+    {}
+    PolicyResult policyResult;
+    int ruleId;
+};
+
+typedef boost::optional<ExtendedPolicyResult> OptionalExtendedPolicyResult;
+
+#endif // _SRC_ACCESS_CONTROL_COMMON_POLICY_RESULT_H_
diff --git a/ace/include/ace/PolicySet.h b/ace/include/ace/PolicySet.h
new file mode 100644 (file)
index 0000000..de12394
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PolicySet.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_POLICYSET_H)
+#define _POLICYSET_H
+
+#include "Policy.h"
+#include <iostream>
+
+class PolicySet : public Policy
+{
+  public:
+
+    //TODO Clean this class
+    //PolicySet(CombineAlgorithm algorithm, std::list<Attribute> * targetAttr,const std::string & subjectId)
+    //        : Policy(algorithm,targetAttr,subjectId)
+    //    {}
+    PolicySet()
+    {
+    }
+    ~PolicySet()
+    {
+    }
+};
+
+#endif  //_POLICYSET_H
diff --git a/ace/include/ace/Preference.h b/ace/include/ace/Preference.h
new file mode 100644 (file)
index 0000000..c37fce8
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Preference.h
+//  @ Date : 2009-05-2
+//  @ Author : Samsung
+//
+//
+
+#ifndef _Preference_H_
+#define _Preference_H_
+
+#include <map>
+#include <string>
+
+#include <ace-dao-ro/PreferenceTypes.h>
+
+typedef AceDB::PreferenceTypes Preference;
+typedef AceDB::PreferenceTypesMap PreferenceMap;
+
+#endif  //_Preference_H
+
diff --git a/ace/include/ace/PromptDecision.h b/ace/include/ace/PromptDecision.h
new file mode 100644 (file)
index 0000000..9bdae43
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+#ifndef _SRC_ACCESS_CONTROL_COMMON_PROMPT_DECISION_H_
+#define _SRC_ACCESS_CONTROL_COMMON_PROMPT_DECISION_H_
+
+#include <boost/optional.hpp>
+#include <dpl/optional_typedefs.h>
+
+enum class PromptDecision {
+    ALLOW_ALWAYS,
+    DENY_ALWAYS,
+    ALLOW_THIS_TIME,
+    DENY_THIS_TIME,
+    ALLOW_FOR_SESSION,
+    DENY_FOR_SESSION
+};
+
+typedef boost::optional<PromptDecision> OptionalPromptDecision;
+
+struct CachedPromptDecision {
+    PromptDecision decision;
+    DPL::OptionalString session;
+};
+
+typedef boost::optional<CachedPromptDecision> OptionalCachedPromptDecision;
+
+#endif // _SRC_ACCESS_CONTROL_COMMON_PROMPT_DECISION_H_
diff --git a/ace/include/ace/Request.h b/ace/include/ace/Request.h
new file mode 100644 (file)
index 0000000..5e5fa9a
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Request.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _REQUEST_H_
+#define _REQUEST_H_
+
+#include <set>
+#include <string>
+#include <vector>
+
+#include <ace-dao-ro/IRequest.h>
+#include <ace/WRT_INTERFACE.h>
+
+class Request : public AceDB::IRequest
+{
+  public:
+    typedef std::string DeviceCapability;
+    typedef std::set<DeviceCapability> DeviceCapabilitySet;
+
+    enum ApplicationType {
+        APP_TYPE_TIZEN,
+        APP_TYPE_WAC20,
+        APP_TYPE_UNKNOWN
+    };
+
+    Request(WidgetHandle widgetHandle,
+            WidgetExecutionPhase phase,
+            IFunctionParam *functionParam = 0)
+      : m_widgetHandle(widgetHandle)
+      , m_phase(phase)
+      , m_functionParam(functionParam)
+      , m_appType(APP_TYPE_UNKNOWN)
+    {}
+
+    WidgetHandle getWidgetHandle() const
+    {
+        return m_widgetHandle;
+    }
+
+    WidgetExecutionPhase getExecutionPhase() const
+    {
+        return m_phase;
+    }
+
+    IFunctionParam *getFunctionParam() const
+    {
+        return m_functionParam;
+    }
+
+    void addDeviceCapability(const std::string& device)
+    {
+        m_devcapSet.insert(device);
+    }
+
+    DeviceCapabilitySet getDeviceCapabilitySet() const
+    {
+        return m_devcapSet;
+    }
+
+    void setAppType(ApplicationType appType)
+    {
+        m_appType = appType;
+    }
+
+    ApplicationType getAppType() const
+    {
+        return m_appType;
+    }
+
+  private:
+    WidgetHandle m_widgetHandle;
+    WidgetExecutionPhase m_phase;
+    //! \brief list of function param (only for intercept)
+    IFunctionParam *m_functionParam;
+    //! \brief Set of defice capabilities
+    DeviceCapabilitySet m_devcapSet;
+    ApplicationType m_appType;
+};
+
+typedef std::vector <Request> Requests;
+
+#endif  //_REQUEST_H_
diff --git a/ace/include/ace/Rule.h b/ace/include/ace/Rule.h
new file mode 100644 (file)
index 0000000..dc64389
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Rule.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_RULE_H)
+#define _RULE_H
+
+#include "Attribute.h"
+#include "Effect.h"
+#include "Condition.h"
+#include <dpl/assert.h>
+
+class Rule : public AbstractTreeElement
+{
+  public:
+
+    ExtendedEffect evaluateRule(const AttributeSet * attrSet) const;
+
+    Rule()
+      : effect(Inapplicable)
+    {
+        //TODO we should set it to deny or smth, not inapplicable
+    }
+
+    void setEffect(ExtendedEffect effect)
+    {
+        //We should not allow to set "Inapplicable" effect.
+        //Rules cannot have effect that is inapplicable, evaluation of the rules may however
+        //render the effect inapplicable.
+        Assert(effect.getEffect() != Inapplicable);
+        this->effect = effect;
+    }
+    void setCondition(Condition condition)
+    {
+        this->condition = condition;
+    }
+    void getAttributes(AttributeSet * attrSet)
+    {
+        condition.getAttributes(attrSet);
+    }
+
+    //DEBUG methods
+    std::string printEffect(const ExtendedEffect &effect) const;
+    void printData();
+
+  private:
+
+    ExtendedEffect effect;
+    Condition condition;
+};
+
+#endif  //_RULE_H
diff --git a/ace/include/ace/SettingsLogic.h b/ace/include/ace/SettingsLogic.h
new file mode 100644 (file)
index 0000000..e0d1fdb
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       SettingsLogic.h
+ * @author     Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version    0.1
+ * @brief      Header file for class getting/setting user/global ACE settings
+ */
+
+#ifndef WRT_SRC_ACCESS_CONTROL_LOGIC_SETTINGS_LOGIC_H_
+#define WRT_SRC_ACCESS_CONTROL_LOGIC_SETTINGS_LOGIC_H_
+
+#include <set>
+#include <list>
+#include <map>
+#include <string>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace/Request.h>
+#include <ace/PermissionTriple.h>
+#include <ace-dao-rw/AceDAO.h>
+#include <ace-dao-ro/common_dao_types.h>
+
+class SettingsLogic
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, DatabaseError)
+    };
+
+    // global settings
+    static AceDB::PreferenceTypes findGlobalUserSettings(
+            const std::string &resource,
+            WidgetHandle handler);
+
+    static AceDB::PreferenceTypes findGlobalUserSettings(
+            const Request &request);
+
+    // resource settings
+    static AceDB::PreferenceTypes getDevCapSetting(
+            const std::string &request);
+    static void getDevCapSettings(AceDB::PreferenceTypesMap *preferences);
+    static void setDevCapSetting(const std::string &resource,
+            AceDB::PreferenceTypes preference);
+    static void setAllDevCapSettings(
+            const std::list<std::pair<const std::string *,
+                    AceDB::PreferenceTypes> > &resourcesList);
+    static void removeDevCapSetting(const std::string &resource);
+    static void updateDevCapSetting(const std::string &resource,
+            AceDB::PreferenceTypes p);
+
+    // user settings
+    static AceDB::PreferenceTypes getWidgetDevCapSetting(
+            const std::string &resource,
+            WidgetHandle handler);
+    static void getWidgetDevCapSettings(PermissionList *permissions);
+    static void setWidgetDevCapSetting(const std::string &resource,
+            WidgetHandle handler,
+            AceDB::PreferenceTypes preference);
+    static void setWidgetDevCapSettings(const PermissionList &tripleList);
+    static void removeWidgetDevCapSetting(const std::string &resource,
+            WidgetHandle handler);
+
+  private:
+    SettingsLogic()
+    {
+    }
+
+};
+
+#endif /* WRT_SRC_ACCESS_CONTROL_LOGIC_SETTINGS_LOGIC_H_ */
diff --git a/ace/include/ace/Subject.h b/ace/include/ace/Subject.h
new file mode 100644 (file)
index 0000000..5176c99
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+// File:   Subject.h
+// Author: notroot
+//
+// Created on June 2, 2009, 8:47 AM
+//
+
+#ifndef _SUBJECT_H
+#define    _SUBJECT_H
+
+#include <set>
+#include <list>
+#include <iostream>
+#include <dpl/assert.h>
+#include <dpl/noncopyable.h>
+
+#include "Attribute.h"
+
+class Subject : DPL::Noncopyable
+{
+    std::string subjectId;
+    std::list<Attribute> targetAttributes;
+
+  public:
+    Subject()
+    {}
+
+    const std::list<Attribute>& getTargetAttributes() const;
+
+    void setSubjectId(const std::string & subjectId)
+    {
+        this->subjectId = subjectId;
+    }
+
+    //TODO maybe we should remove that becuase this causes a memory leak right now!! [CR] maybe thats true, maybe whe can remove this fun
+    // KW    void setTargetAttributes(std::list<Attribute> * targetAttributes){ this->targetAttributes = targetAttributes; }
+
+    const std::string & getSubjectId() const
+    {
+        return this->subjectId;
+    }
+
+    void addNewAttribute(Attribute & attr)
+    {
+        this->targetAttributes.push_back(attr);
+    }
+
+    //TODO in 1.0 change to true/false/undetermined
+    bool matchSubject(const AttributeSet *attrSet,
+            bool &isUndetermined) const;
+
+    ~Subject()
+    {}
+};
+
+#endif    /* _SUBJECT_H */
+
diff --git a/ace/include/ace/TestTimer.h b/ace/include/ace/TestTimer.h
new file mode 100644 (file)
index 0000000..1f07e61
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#ifndef _TEST_TIMER_H
+#define _TEST_TIMER_H
+
+#include <time.h>
+
+class TestTimer
+{
+    time_t startt, endt;
+
+  public:
+    void start()
+    {
+        time(&startt);
+    }
+    void stop()
+    {
+        time(&endt);
+    }
+    double getTime()
+    {
+        return difftime(endt, startt);
+    }
+};
+
+#endif  //_TEST_TIMER_H
+
diff --git a/ace/include/ace/TreeNode.h b/ace/include/ace/TreeNode.h
new file mode 100644 (file)
index 0000000..473c26f
--- /dev/null
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : TreeNode.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _TREE_NODE_H
+#define _TREE_NODE_H
+
+#include <iostream>
+#include <list>
+
+#include <ace/AbstractTreeElement.h>
+
+class TreeNode;
+
+typedef std::list<TreeNode *> ChildrenSet;
+typedef std::list<TreeNode *>::iterator ChildrenIterator;
+typedef std::list<TreeNode *>::const_iterator ChildrenConstIterator;
+
+class TreeNode
+{
+  public:
+    //TODO nazwac pozadnie TYPY - moze jakas konwencja ... ??!!
+    enum TypeID { Policy =0, PolicySet=1, Rule=2};
+
+    const ChildrenSet  & getChildrenSet() const
+    {
+        return children;
+    }
+
+    TreeNode * getParent() const
+    {
+        return this->parent;
+    }
+
+    void setParent(TreeNode *parent)
+    {
+        this->parent = parent;
+    }
+
+    TypeID getTypeID() const
+    {
+        return this->typeID;
+    }
+
+    void addChild(TreeNode *child)
+    {
+        child->setParent(this);
+        children.push_back(child);
+    }
+
+    /**
+     * Clone the node
+     */
+    // KW        TreeNode * clone() { return new TreeNode(NULL,this->getTypeID(),this->getElement()); }
+
+    TreeNode(TreeNode * parent,
+            TypeID type,
+            AbstractTreeElement * element) :
+        parent(parent),
+        typeID(type),
+        element(element)
+    {
+    }
+
+    AbstractTreeElement * getElement() const
+    {
+        return element;
+    }
+
+  private:
+    virtual ~TreeNode();
+
+  public:
+    /*
+     * It is common that we create a copy of tree structure created out of xml file. However we don't want to
+     * copy abstract elements ( Policies and Rules ) because we need them only for reading. We want to modify the
+     * tree structure though. Therefore we copy TreeNode. When the copy of the original tree is being destroyed method
+     * releaseTheSubtree should be called on "root". It automatically traverse the tree and call TreeNode destructors for
+     * each TreeNode in the tree. It doesn't remove the abstract elements in the tree ( there is always at most one abstract
+     * element instance, when tree is copied it is a shallow copy.
+     * When we want to completely get rid of the the tree and abstract elements we have to call releaseResources on tree root.
+     * We may want to do this for instance when we want to serialize the tree to disc. releaseResource method traverses the tree
+     * and releses the resources, as well as the TreeNode so NO releaseTheSubtree is required any more
+     */
+    void releaseResources();
+
+    /**
+     * Used to delete the copies of tree structure. The original tree structure should be removed with releaseResources method.
+     * ReleaseTheSubtree method doesn't delete the abstract elements, only TreeNodes. It traverses the whole tree, so it should be
+     * called on behalf of root of the tree
+     */
+    // KW        void releaseTheSubtree();
+
+    friend std::ostream & operator<<(std::ostream & out,
+            const TreeNode * node);
+    // KW        void printSubtree();
+
+  private:
+    // KW    TreeNode(const TreeNode& pattern){ (void)pattern; }
+
+    std::list<TreeNode *> children;
+    TreeNode * parent;
+    //TODO standarize ID case
+    TypeID typeID;
+    AbstractTreeElement * element;
+    static int level;
+};
+
+#endif  //_TREE_NODE_H
diff --git a/ace/include/ace/UserDecision.h b/ace/include/ace/UserDecision.h
new file mode 100644 (file)
index 0000000..67bdbcf
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : UserDecision.h
+//  @ Date : 2009-05-22
+//  @ Author : Samsung
+//
+//
+
+#ifndef _USERDECISION_H
+#define _USERDECISION_H
+
+#include <ace/Verdict.h>
+#include <ace-dao-ro/ValidityTypes.h>
+
+typedef AceDB::ValidityTypes Validity;
+
+const char * toString(Validity validity);
+
+#endif  //_USERDECISION_H
+
diff --git a/ace/include/ace/Verdict.h b/ace/include/ace/Verdict.h
new file mode 100644 (file)
index 0000000..83d2d79
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Verdict.h
+//  @ Date : 2009-05-2
+//  @ Author : Samsung
+//
+//
+
+#ifndef _VERDICT_H
+#define _VERDICT_H
+
+#include <string>
+#include <ace-dao-ro/VerdictTypes.h>
+#include <ace-dao-ro/TimedVerdict.h>
+
+typedef AceDB::VerdictTypes Verdict;
+//typedef AceDB::TimedVerdict TimedVerdict;
+
+const char * toString(Verdict verditct);
+
+#endif  //_VERDICT_H
+
diff --git a/ace/include/ace/WRT_INTERFACE.h b/ace/include/ace/WRT_INTERFACE.h
new file mode 100644 (file)
index 0000000..ac8ab93
--- /dev/null
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#ifndef _WRT_INERFACE_4_ACE_EXAMPLE_H_
+#define _WRT_INERFACE_4_ACE_EXAMPLE_H_
+
+#include <list>
+#include <map>
+#include <string>
+
+typedef int WidgetHandle;
+
+class Request;
+
+enum WidgetExecutionPhase
+{
+    WidgetExecutionPhase_Unknown           = 0,
+    WidgetExecutionPhase_WidgetInstall     = 1 << 0,
+    WidgetExecutionPhase_WidgetInstantiate = 1 << 1,
+    WidgetExecutionPhase_WebkitBind        = 1 << 2,
+    WidgetExecutionPhase_Invoke            = 1 << 3
+};
+
+struct RequestContext
+{
+    const WidgetHandle Handle;
+    WidgetExecutionPhase Phase;
+
+    RequestContext(WidgetHandle handle,
+            WidgetExecutionPhase phase) :
+        Handle(handle),
+        Phase(phase)
+    {
+    }
+};
+
+// Pair of pointer to attribute name and pointer to list of value for
+// this attribute name
+typedef std::pair< const std::string* const, std::list<std::string>* >
+ATTRIBUTE;
+
+/*
+ * Each function should return 0 as success and positive value as error
+ *
+ * Possible return value:
+ * 0 - succes
+ * 1 - subjectId/resourceId name unknown
+ * 2 - unknown attribute name
+ * 4 - interface error
+ **/
+
+/************** Web Runtime ********************/
+
+class IWebRuntime
+{
+  public:
+
+    /**
+     * gather and set attributes values for specified subjectId
+     * and attribute name
+     * @param subjectId is a name of subject (widget or internet site URI )
+     * @param attributes is a list of pairs(
+     *   first:   pointer to attribute name
+     *   second: list of values for attribute (std::string)   -
+     *   its a list of string (BONDI requirement), but usually there will
+     *   be only one string
+     * */
+    virtual int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE> *attributes) = 0;
+
+    /*return current sessionId */
+    virtual std::string getSessionId(const Request &request) = 0;
+
+    virtual ~IWebRuntime()
+    {
+    }
+};
+
+/************** Resource Information ********************/
+class IResourceInformation
+{
+  public:
+    /**
+     * gather and set attributes values for specified resourceId
+     * and attribute name
+     * @param resourceId is a name of subject (widget or internet site URI )
+     * @param attributes is a list of pairs(
+     *   first:   pointer to attribute name
+     *   second: list of values for attribute (std::string)  -
+     *   its a list of string (BONDI requirement), but usually there will
+     *   be only one string
+     * */
+    virtual int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE> *attributes) = 0;
+
+    virtual ~IResourceInformation()
+    {
+    }
+};
+
+/**************  Operation System  ********************/
+class IOperationSystem
+{
+  public:
+
+    /**
+     * gather and set attributes values for specified attribute name
+     * @param attributes is a list of pairs(
+     *   first:   pointer to attribute name
+     *   second: list of values for attribute (std::string)  -
+     *   its a list of string (BONDI requirement), but usually
+     *   there will be only one string
+     * */
+    virtual int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE> *attributes) = 0;
+
+    virtual ~IOperationSystem()
+    {
+    }
+};
+
+class IFunctionParam
+{
+  public:
+    virtual int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE> *attributes) = 0;
+    virtual ~IFunctionParam()
+    {
+    }
+};
+
+#endif //_WRT_INERFACE_4_ACE_EXAMPLE_H_
diff --git a/ace/include/ace/WidgetUsageModel.h b/ace/include/ace/WidgetUsageModel.h
new file mode 100644 (file)
index 0000000..094e6ab
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//  @ Project : Access Control Engine
+//  @ File Name : UserDecision.h
+//  @ Date : 2009-05-22
+//  @ Author : Samsung
+//
+//
+
+#ifndef _WIDGET_USAGE_H
+#define _WIDGET_USAGE_H
+
+#ifdef DBUS_CONNECTION
+#include <dpl/event/event_support.h>
+#endif
+
+#include "Request.h"
+#include "AsyncVerdictResultListener.h"
+
+enum UsageValidity
+{
+    USAGE_UNKNOWN,
+    USAGE_ONCE,
+    USAGE_SESSION,
+    USAGE_ALWAYS
+};
+
+enum UsageVerdict
+{
+    USAGE_VERDICT_PERMIT,
+    USAGE_VERDICT_DENY,
+    USAGE_VERDICT_INAPPLICABLE,
+    USAGE_VERDICT_UNDETERMINED,
+    USAGE_VERDICT_UNKNOWN,
+    USAGE_VERDICT_ERROR
+};
+//Forward declaration
+class PolicyEvaluator;
+
+class PolicyEvaluatorData
+{
+  private:
+    Request m_request;
+    UsageValidity m_validity;
+    UsageVerdict m_verdict;
+    AsyncVerdictResultListener *m_listener;
+  public:
+
+    PolicyEvaluatorData(const Request& request,
+            AsyncVerdictResultListener *listener) :
+        m_request(request),
+        m_validity(USAGE_UNKNOWN),
+        m_verdict(USAGE_VERDICT_ERROR),
+        m_listener(listener)
+    {
+    }
+
+    // KW     UsageValidity getValidity() const {
+    // KW         return m_validity;
+    // KW     }
+    // KW
+    // KW     UsageVerdict getVerdict() const {
+    // KW         return m_verdict;
+    // KW     }
+    // KW
+    // KW     void setValidity(UsageValidity validity) {
+    // KW         this->m_validity = validity;
+    // KW     }
+    // KW
+    // KW     void setVerdict(UsageVerdict verdict) {
+    // KW         this->m_verdict = verdict;
+    // KW     }
+
+    const Request& getRequest() const
+    {
+        return m_request;
+    }
+
+    AsyncVerdictResultListener* getListener() const
+    {
+        return m_listener;
+    }
+};
+
+#endif  //_USERDECISION_H
diff --git a/ace/include/ace/acf_consts.h b/ace/include/ace/acf_consts.h
new file mode 100644 (file)
index 0000000..93ecfae
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * This file contain consts for Signing Template and Policy Manager
+ * This values will be used to specified and identified algorithms in xml policy documents.
+ * Its consistent with BONDI 1.0 released requirements
+ *
+ * NOTE: This values should be verified when ACF will be updated to the latest version of BONDI requirements
+ * This values comes from widget digital signature 1.0 - required version of this doc is very important
+ *
+ **/
+
+#ifndef ACF_CONSTS_TYPES_H
+#define ACF_CONSTS_TYPES_H
+
+//Digest Algorithms
+extern const char* DIGEST_ALG_SHA256;
+
+//Canonicalization Algorithms
+extern const char* CANONICAL_ALG_C14N;
+
+//Signature Algorithms
+extern const char* SIGNATURE_ALG_RSA_with_SHA256;
+extern const char* SIGNATURE_ALG_DSA_with_SHA1;
+extern const char* SIGNATURE_ALG_ECDSA_with_SHA256;
+
+#endif
+
diff --git a/ace/include/ace/parser.h b/ace/include/ace/parser.h
new file mode 100644 (file)
index 0000000..26f15e2
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : parser.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _PARSER_H_
+#define _PARSER_H_
+
+//#include "/usr/include/libxml2/libxml/parser.h"
+#include <string>
+#include <libxml/xmlreader.h>
+#include <libxml/c14n.h>
+#include <libxml/xpath.h>
+#include <libxml/xpathInternals.h>
+
+#include "Policy.h"
+#include "PolicySet.h"
+#include "Request.h"
+#include "Rule.h"
+#include "Attribute.h"
+#include "TreeNode.h"
+#include "Subject.h"
+#include "Condition.h"
+#include "Effect.h"
+
+#define whitespaces " \n\t\r"
+
+enum CanonicalizationAlgorithm
+{
+    C14N,
+    C14NEXCLUSIVE
+};
+
+class Parser
+{
+  private:
+    RuleId ruleId;
+    xmlTextReaderPtr reader;
+
+    TreeNode * root;
+    TreeNode * currentRoot;
+    Subject * currentSubject;
+    Condition * currentCondition;
+    Attribute * currentAttribute;
+    std::string * currentText;
+
+    bool processingSignature;
+    bool canonicalizeOnce;
+
+    void processNode(xmlTextReaderPtr reader);
+
+    //Node Handlers
+    void endNodeHandler(xmlTextReaderPtr reader);
+    void textNodeHandler(xmlTextReaderPtr reader);
+    void startNodeHandler(xmlTextReaderPtr reader);
+
+    //Node names handlers
+    void handleAttr(xmlTextReaderPtr reader);
+    void handleRule(xmlTextReaderPtr reader);
+    void handleSubject();
+    void handleCondition(xmlTextReaderPtr reader);
+    void handleSubjectMatch(xmlTextReaderPtr reader);
+    void handleMatch(xmlTextReaderPtr reader,
+            Attribute::Type);
+    void handlePolicy(xmlTextReaderPtr reader,
+            TreeNode::TypeID type);
+
+    //helpers
+    Policy::CombineAlgorithm convertToCombineAlgorithm(xmlChar*);
+    ExtendedEffect convertToEffect(xmlChar *effect);
+    Attribute::Match convertToMatchFunction(xmlChar * func);
+    void consumeCurrentText();
+    void consumeCurrentAttribute();
+    void consumeSubjectMatch(xmlChar * value = NULL);
+    void consumeCurrentSubject();
+    void consumeCurrentCondition();
+    void trim(std::string *);
+    // KW     void canonicalize(const char *, const char *, CanonicalizationAlgorithm canonicalizationAlgorithm);
+    // KW     int extractNodeToFile(xmlTextReaderPtr reader, const char * filename);
+
+    static const char *TOKEN_PARAM;
+  public:
+    Parser();
+    ~Parser();
+    TreeNode * parse(const std::string& filename, const std::string& schema);
+};
+
+#endif  //_PARSER_H
diff --git a/ace/orm/ace_db b/ace/orm/ace_db
new file mode 100644 (file)
index 0000000..7f90ed4
--- /dev/null
@@ -0,0 +1,92 @@
+SQL(
+    PRAGMA foreign_keys = ON;
+    BEGIN TRANSACTION;
+)
+
+CREATE_TABLE(AcePolicyResult)
+    COLUMN_NOT_NULL(decision,       INTEGER,    check(decision between 0 and 6))
+    COLUMN_NOT_NULL(hash,           TEXT,)
+    COLUMN_NOT_NULL(rule_id,        INTEGER)
+    TABLE_CONSTRAINTS(
+        PRIMARY KEY(hash)
+    )
+CREATE_TABLE_END()
+
+CREATE_TABLE(AcePromptDecision)
+    COLUMN_NOT_NULL(app_id,         INTEGER,)
+    COLUMN_NOT_NULL(decision,       INTEGER,   check(decision between 0 and 5))
+    COLUMN(session,                 TEXT,)
+    COLUMN_NOT_NULL(rule_id,        INTEGER,)
+    TABLE_CONSTRAINTS(
+        PRIMARY KEY(app_id,rule_id)
+    )
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceAttribute)
+    COLUMN_NOT_NULL(attr_id,        INTEGER,    primary key autoincrement)
+    COLUMN_NOT_NULL(name,           TEXT,)
+    COLUMN_NOT_NULL(type,           INTEGER,    check(type between 0 and 4))
+
+    TABLE_CONSTRAINTS(unique(name,type))
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceSubject)
+    COLUMN_NOT_NULL(subject_id,     INTEGER,    primary key autoincrement)
+    COLUMN_NOT_NULL(id_uri,         TEXT,       unique)
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceDevCap)
+    COLUMN_NOT_NULL(resource_id,    INTEGER,    primary key autoincrement)
+    COLUMN_NOT_NULL(id_uri,         TEXT,       unique)
+    COLUMN_NOT_NULL(general_setting,INTEGER,    check(general_setting between -1 and 4))
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceWidgetDevCapSetting)
+    COLUMN_NOT_NULL(app_id,         INTEGER,    not null)
+    COLUMN_NOT_NULL(resource_id,    INTEGER,    references AceDevCap(resource_id))
+    COLUMN_NOT_NULL(access_value,   INTEGER,    check(access_value between -1 and 4))
+
+    TABLE_CONSTRAINTS(unique(app_id,resource_id))
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceRequestedDevCaps)
+    COLUMN_NOT_NULL(app_id,        INTEGER,  not null)
+    COLUMN_NOT_NULL(grant_smack,   INTEGER,  not null)
+    COLUMN_NOT_NULL(dev_cap,       TEXT,)
+
+    TABLE_CONSTRAINTS(unique(app_id,dev_cap))
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceAcceptedFeature)
+    COLUMN_NOT_NULL(app_id,        INTEGER,  not null)
+    COLUMN_NOT_NULL(feature,       TEXT,     not null)
+
+    TABLE_CONSTRAINTS(unique(app_id,feature))
+CREATE_TABLE_END()
+
+CREATE_TABLE(WidgetInfo)
+    COLUMN_NOT_NULL(app_id,         INTEGER,      PRIMARY KEY)
+    COLUMN(widget_type,             INT,          DEFAULT 1)
+    COLUMN(widget_id,               VARCHAR(256), DEFAULT '')
+    COLUMN(widget_version,          VARCHAR(256), DEFAULT '')
+    COLUMN(author_name,             VARCHAR(256), DEFAULT '')
+    COLUMN(share_href,              VARCHAR(256), DEFAULT '')
+CREATE_TABLE_END()
+
+CREATE_TABLE(WidgetCertificateFingerprint)
+    COLUMN_NOT_NULL(app_id,     INT,)
+    COLUMN_NOT_NULL(owner,      INT,)
+    COLUMN_NOT_NULL(chainid,    INT,)
+    COLUMN_NOT_NULL(type,       INT,)
+    COLUMN(md5_fingerprint,     VARCHAR(64),)
+    COLUMN(sha1_fingerprint,    VARCHAR(64),)
+    COLUMN(common_name,         VARCHAR(64),)
+    TABLE_CONSTRAINTS(
+        PRIMARY KEY (app_id, chainid, owner, type)
+        FOREIGN KEY (app_id) REFERENCES WidgetInfo (app_id) ON DELETE CASCADE
+    )
+CREATE_TABLE_END()
+
+SQL(
+    COMMIT;
+)
diff --git a/ace/orm/ace_db_definitions b/ace/orm/ace_db_definitions
new file mode 100644 (file)
index 0000000..46836e9
--- /dev/null
@@ -0,0 +1,6 @@
+DATABASE_START(ace)
+
+#include "ace_db"
+#include "version_db"
+
+DATABASE_END()
diff --git a/ace/orm/ace_db_sql_generator.h b/ace/orm/ace_db_sql_generator.h
new file mode 100644 (file)
index 0000000..5af05ac
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        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.
+ */
+
+//Do not include this file directly! It is used only for SQL code generation.
+
+#include <dpl/db/orm_macros.h>
+
+#include "ace_db_definitions"
diff --git a/ace/orm/gen_db_md5.sh b/ace/orm/gen_db_md5.sh
new file mode 100755 (executable)
index 0000000..38587b7
--- /dev/null
@@ -0,0 +1,19 @@
+#!/bin/sh
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+CHECKSUM=`cat ${2} ${3} 2>/dev/null | md5sum 2>/dev/null | cut -d\  -f1 2>/dev/null`
+echo "#define DB_CHECKSUM DB_VERSION_${CHECKSUM}" > ${1}
+echo "#define DB_CHECKSUM_STR \"DB_VERSION_${CHECKSUM}\"" >> ${1}
+
diff --git a/ace/orm/orm_generator_ace.h b/ace/orm/orm_generator_ace.h
new file mode 100644 (file)
index 0000000..640dd35
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+#ifndef ORM_GENERATOR_ACE_H
+#define ORM_GENERATOR_ACE_H
+
+#define ORM_GENERATOR_DATABASE_NAME ace_db_definitions
+#include <dpl/db/orm_generator.h>
+#undef ORM_GENERATOR_DATABASE_NAME
+
+#endif
diff --git a/ace/orm/version_db b/ace/orm/version_db
new file mode 100644 (file)
index 0000000..7e20d8d
--- /dev/null
@@ -0,0 +1,5 @@
+SQL(
+    BEGIN TRANSACTION;
+    CREATE TABLE DB_CHECKSUM (version INT);
+    COMMIT;
+)
diff --git a/ace_client/CMakeLists.txt b/ace_client/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4b7537b
--- /dev/null
@@ -0,0 +1 @@
+ADD_SUBDIRECTORY(src)
diff --git a/ace_client/include/ace-client/ace_client.h b/ace_client/include/ace-client/ace_client.h
new file mode 100644 (file)
index 0000000..024be70
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        ace_client.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions of AceThinClient API
+ */
+#ifndef WRT_ACE_CLIENT_H
+#define WRT_ACE_CLIENT_H
+
+#include <dpl/noncopyable.h>
+#include <dpl/singleton.h>
+#include <dpl/exception.h>
+#include <ace-client/ace_client_types.h>
+
+class WebRuntimeImpl;
+class ResourceInformationImpl;
+class OperationSystemImpl;
+
+namespace AceClient {
+
+class AceThinClientImpl;
+
+class AceThinClient : private DPL::Noncopyable {
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, AceThinClientException)
+    };
+
+    bool checkFunctionCall(const AceRequest& ace_request) const;
+    bool checkPrivacy(const AceRequest& ace_request) const;
+    AcePreference getWidgetResourcePreference(
+            const AceResource& resource,
+            const AceWidgetHandle& handle) const;
+    AceResourcesPreferences* getGlobalResourcesPreferences() const;
+    bool isInitialized() const;
+
+  private:
+    AceThinClient();
+    virtual ~AceThinClient();
+
+    AceThinClientImpl* m_impl;
+    friend class DPL::Singleton<AceThinClient>;
+    WebRuntimeImpl* m_wrt;
+    ResourceInformationImpl* m_res;
+    OperationSystemImpl* m_sys;
+};
+
+typedef DPL::Singleton<AceThinClient> AceThinClientSingleton;
+
+} // namespace AceClient
+
+#endif // WRT_ACE_CLIENT_H
diff --git a/ace_client/include/ace-client/ace_client_helper.h b/ace_client/include/ace-client/ace_client_helper.h
new file mode 100644 (file)
index 0000000..14c5964
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        ace_client_helper.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions of AceClient helper types and
+ *              functions.
+ */
+#ifndef WRT_ACE_CLIENT_HELPER_H
+#define WRT_ACE_CLIENT_HELPER_H
+
+#include <string>
+#include <vector>
+#include <dpl/foreach.h>
+
+#include <ace-dao-ro/IRequest.h>
+#include <ace-dao-ro/PreferenceTypes.h>
+
+#include "ace_client_types.h"
+
+namespace AceClient {
+
+AcePreference toAcePreference(AceDB::PreferenceTypes preference)
+{
+    switch (preference) {
+    case AceDB::PreferenceTypes::PREFERENCE_PERMIT: {
+        return PREFERENCE_PERMIT; }
+    case AceDB::PreferenceTypes::PREFERENCE_DENY: {
+        return PREFERENCE_DENY; }
+    case AceDB::PreferenceTypes::PREFERENCE_DEFAULT: {
+        return PREFERENCE_DEFAULT; }
+    case AceDB::PreferenceTypes::PREFERENCE_BLANKET_PROMPT: {
+        return PREFERENCE_BLANKET_PROMPT; }
+    case AceDB::PreferenceTypes::PREFERENCE_SESSION_PROMPT: {
+        return PREFERENCE_SESSION_PROMPT; }
+    case AceDB::PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT: {
+        return PREFERENCE_ONE_SHOT_PROMPT; }
+    }
+    return PREFERENCE_DEFAULT;
+}
+
+typedef std::vector<std::string> AceParamKeys;
+typedef std::vector<std::string> AceParamValues;
+
+class AceFunctionParam
+{
+  public:
+    virtual ~AceFunctionParam()
+    {
+    }
+
+    void addAttribute(const std::string& key,
+                      const std::string& value)
+    {
+        m_paramMap.insert(std::make_pair(key, value));
+    }
+
+    AceParamKeys getKeys() const
+    {
+        AceParamKeys out;
+        FOREACH (it, m_paramMap) {
+            out.push_back(it->first);
+        }
+        return out;
+    }
+
+    AceParamValues getValues() const
+    {
+        AceParamValues out;
+        FOREACH (it, m_paramMap) {
+            out.push_back(it->second);
+        }
+        return out;
+    }
+
+    static std::string aceFunctionParamToken;
+
+  private:
+    typedef std::multimap<std::string, std::string> ParamMap;
+    ParamMap m_paramMap;
+};
+
+typedef std::vector <AceFunctionParam> AceFunctionParams;
+
+class AceBasicRequest : public AceDB::IRequest {
+  public:
+    AceBasicRequest(const AceSubject& subject,
+                    const AceResource& resource) :
+      m_subject(subject),
+      m_resource(resource)
+    {
+    }
+
+    AceBasicRequest(const AceSubject& subject,
+                    const AceResource& resource,
+                    const AceFunctionParam& param) :
+      m_subject(subject),
+      m_resource(resource),
+      m_param(param)
+    {
+    }
+    virtual const std::string& getSubjectId() const
+    {
+        return m_subject;
+    }
+    virtual const std::string& getResourceId() const
+    {
+        return m_resource;
+    }
+    virtual const AceFunctionParam& getFunctionParam() const
+    {
+        return m_param;
+    }
+
+  private:
+    AceSubject m_subject;
+    AceResource m_resource;
+    AceFunctionParam m_param;
+};
+
+typedef std::vector <AceBasicRequest> AceBasicRequests;
+
+} // namespace AceClient
+
+#endif // WRT_ACE_CLIENT_HELPER_H
diff --git a/ace_client/include/ace-client/ace_client_types.h b/ace_client/include/ace-client/ace_client_types.h
new file mode 100644 (file)
index 0000000..f27a4ba
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        ace_client_types.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions of AceClient types
+ */
+#ifndef WRT_ACE_CLIENT_TYPES_H
+#define WRT_ACE_CLIENT_TYPES_H
+
+#include <string>
+#include <utility>
+#include <map>
+
+namespace AceClient {
+
+typedef int   AceWidgetHandle;
+typedef void* AceJobWidgetInstallId;
+
+typedef std::string AceResource;
+typedef std::string AceSubject;
+typedef std::string AceSessionId;
+
+enum AcePreference
+{
+    PREFERENCE_PERMIT,
+    PREFERENCE_DENY,
+    PREFERENCE_DEFAULT,
+    PREFERENCE_BLANKET_PROMPT,
+    PREFERENCE_SESSION_PROMPT,
+    PREFERENCE_ONE_SHOT_PROMPT
+};
+
+typedef std::map<std::string, AcePreference>  AceResourcesPreferences;
+typedef std::pair<std::string, AcePreference> AceResurcePreference;
+
+struct AceParam
+{
+    const char *name;
+    const char *value;
+
+    AceParam():
+        name(NULL), value(NULL)
+    {}
+
+    AceParam(const char *name, const char *value):
+        name(name), value(value)
+    {}
+};
+
+struct AceParamList
+{
+    size_t    count;
+    AceParam* param;
+    AceParamList():
+        count(0),
+        param(NULL)
+    {}
+};
+
+struct AceDeviceCap
+{
+    size_t        devcapsCount;
+    const char**  devCapNames;
+    size_t        paramsCount;
+    AceParamList* params;
+    AceDeviceCap():
+        devcapsCount(0),
+        devCapNames(NULL),
+        paramsCount(0),
+        params(NULL)
+    {}
+};
+
+struct AceApiFeatures
+{
+    size_t       count;
+    const char** apiFeature;
+    AceApiFeatures():
+        count(0),
+        apiFeature(NULL)
+    {}
+};
+
+struct AceRequest
+{
+    AceSessionId    sessionId;
+    AceWidgetHandle widgetHandle;
+    AceApiFeatures  apiFeatures;
+    const char*     functionName;
+    AceDeviceCap    deviceCapabilities;
+    AceRequest():
+        widgetHandle(0),
+        apiFeatures(),
+        functionName(NULL),
+        deviceCapabilities()
+    {}
+};
+
+} // namespace AceClient
+
+#endif // WRT_ACE_CLIENT_TYPES_H
diff --git a/ace_client/include/ace_api_client.h b/ace_client/include/ace_api_client.h
new file mode 100644 (file)
index 0000000..a952add
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_api_client.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This is C api for Access Control Engine (ACE), client mode
+ *              (RO part).
+ */
+
+#ifndef ACE_API_CLIENT_H
+#define ACE_API_CLIENT_H
+
+#include <ace_api_common.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * API defined in this header should be used only from one thread. If used
+ * otherwise, unexpected behaviour may occur, including segmentation faults and
+ * escalation of global warming. Be warned.
+ */
+
+// --------------- Initialization and deinitialization -------------------------
+
+/*
+ * Function type that must be implemented externally and passed to ACE
+ * on initialization. This function must show to the user a popup with
+ * information on access request to single device capability. Will be used by
+ * implementation of ace_check_access API, when policy requires to display
+ * popup.
+ *
+ * Function must be synchronous and must behave accordingly:
+ *
+ * Function may return value other than ACE_OK, but it will be treated as
+ * denial of access.
+ *
+ * If returned value is ACE_OK, then 'validation_result' must hold information
+ * on whether the access was granted or not.
+ *
+ * Executed function must display a popup with readable information presented to
+ * user, covering 'resource_name' that is to be accessed for 'handle' widget
+ * which is requesting the access.
+ *
+ * In its implementation, after the user answered to displayed question,
+ * UI handler must call popup answer validation API (ace_validate_answer)
+ * from separate, ace-popup-validation library, with passed 'param_list',
+ * 'session_id', 'handle' and given answer as arguments. Validation result
+ * returned by ace_validate_answer needs to be returned in 'validation_result'
+ * parameter of UI handler.
+ *
+ * 'popup_type' describes what kind of options should be given to user - i.e.
+ * ONESHOT prompt only gives possibility to answer Permit/Deny and returned
+ * validity for this prompt must be ONCE. PER_SESSION prompt allows to return
+ * validity ONCE or PER_SESSION. BLANKET prompt allows to return any validity,
+ * as defined in ace_validity_t.
+ *
+ * This call must be made from properly SMACK labelled, safe process - otherwise
+ * the validation will not occur in security daemon and caller will not be
+ * granted access to requested device capability.
+ */
+typedef ace_return_t (*ace_popup_handler_func_t)(
+        ace_popup_t popup_type,
+        const ace_resource_t resource_name,
+        const ace_session_id_t session_id,
+        const ace_param_list_t* param_list,
+        ace_widget_handle_t handle,
+        ace_bool_t* validation_result);
+
+/*
+ * Initializes ACE for check access API (client mode). Must be called only once.
+ * Keep in mind that initializing ACE in client mode disallows usage of API
+ * defined in ace_api.h and ace_api_settings.h (RW part).
+ *
+ * 'handler' must not be NULL, see definition of ace_popup_handler_func_t for
+ * more information.
+ *
+ * Returns error or ACE_OK.
+ */
+ace_return_t ace_client_initialize(ace_popup_handler_func_t handler);
+
+/*
+ * Deinitializes ACE client for check access API. Can be called only once.
+ */
+ace_return_t ace_client_shutdown(void);
+
+// --------------- Check Access API --------------------------------------------
+
+/*
+ * Does ACE check with set of device capabilities and function parameters.
+ * Checks cache first, if it is non-existent, does full ACE check.
+ *
+ * Returns error or ACE_OK and information if access was allowed or not
+ * (value ACE_TRUE or ACE_FALSE is in 'access' argument, only if returned value
+ * is ACE_OK - otherwise, 'access' value is undefined)
+ */
+ace_return_t ace_check_access_ex(const ace_request_t* request, ace_check_result_t* result);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_API_CLIENT_H
diff --git a/ace_client/include/ace_popup_handler.h b/ace_client/include/ace_popup_handler.h
new file mode 100644 (file)
index 0000000..e63630d
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_popup_handler.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       Private header for access to UI handling function.
+ *              (RO part).
+ */
+
+#ifndef ACE_POPUP_HANDLER_H
+#define ACE_POPUP_HANDLER_H
+
+#include <ace_api_client.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern ace_popup_handler_func_t popup_func;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_POPUP_HANDLER_H
diff --git a/ace_client/src/CMakeLists.txt b/ace_client/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..f59e995
--- /dev/null
@@ -0,0 +1,75 @@
+include(FindPkgConfig)
+
+PKG_CHECK_MODULES(ACE_CLIENT_DEPS
+    dpl-efl
+    dpl-event-efl
+    dpl-dbus-efl
+    privacy-manager-client
+    capi-appfw-app-manager
+    capi-appfw-package-manager
+    dpl-wrt-dao-ro
+    REQUIRED
+    )
+
+SET(ACE_CLIENT_DIR
+    ${PROJECT_SOURCE_DIR}/ace_client
+    )
+
+SET(ACE_CLIENT_SRC_DIR
+    ${ACE_CLIENT_DIR}/src
+    )
+
+SET(ACE_CLIENT_INCLUDE_DIR
+    ${ACE_CLIENT_DIR}/include
+    )
+
+SET(ACE_CLIENT_SOURCES
+    ${COMMUNICATION_CLIENT_SOURCES}
+    ${ACE_CLIENT_SRC_DIR}/ace_client.cpp
+    ${ACE_CLIENT_SRC_DIR}/ace_api_client.cpp
+    ${PROJECT_SOURCE_DIR}/src/services/ace/logic/attribute_facade.cpp
+    ${PROJECT_SOURCE_DIR}/src/services/ace/logic/simple_roaming_agent.cpp
+    )
+
+SET(ACE_CLIENT_INCLUDES
+    ${COMMUNICATION_CLIENT_INCLUDES}
+    ${ACE_CLIENT_DEPS_INCLUDE_DIRS}
+    ${ACE_CLIENT_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    ${PROJECT_SOURCE_DIR}/src/services/ace
+    ${PROJECT_SOURCE_DIR}/src/services/ace/
+    ${PROJECT_SOURCE_DIR}/src/services/ace/logic
+    ${PROJECT_SOURCE_DIR}/src/services/popup
+    ${PROJECT_SOURCE_DIR}/popup_process
+    ${PROJECT_SOURCE_DIR}/ace/include
+    )
+
+ADD_DEFINITIONS(${ACE_CLIENT_DEPS_CFLAGS})
+ADD_DEFINITIONS(${ACE_CLIENT_CFLAGS_OTHER})
+
+INCLUDE_DIRECTORIES(${ACE_CLIENT_INCLUDES})
+
+ADD_LIBRARY(${TARGET_ACE_CLIENT_LIB} SHARED ${ACE_CLIENT_SOURCES})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_CLIENT_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_CLIENT_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+TARGET_LINK_LIBRARIES(${TARGET_ACE_CLIENT_LIB}
+    ${ACE_CLIENT_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RO_LIB}
+    ${TARGET_ACE_LIB}
+    )
+
+INSTALL(TARGETS ${TARGET_ACE_CLIENT_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+#    ${ACE_CLIENT_INCLUDE_DIR}/ace-client/ace_client.h
+#    ${ACE_CLIENT_INCLUDE_DIR}/ace-client/ace_client_types.h
+    ${ACE_CLIENT_INCLUDE_DIR}/ace_api_client.h
+    DESTINATION include/ace-client
+    )
diff --git a/ace_client/src/ace_api_client.cpp b/ace_client/src/ace_api_client.cpp
new file mode 100644 (file)
index 0000000..4e8c256
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        ace_api_client.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of ACE client API
+ */
+
+#include <dpl/log/log.h>
+#include <ace_popup_handler.h>
+#include "ace_api_client.h"
+#include "ace-client/ace_client.h"
+
+#include <string>
+#include <vector>
+#include "popup_response_server_api.h"
+#ifdef DBUS_CONNECTION
+#include <dpl/dbus/dbus_client.h>
+#include "security_daemon_dbus_config.h"
+//#include "PromptModel.h"
+#endif
+
+
+ace_return_t ace_client_initialize(ace_popup_handler_func_t handler)
+{
+    if (!AceClient::AceThinClientSingleton::Instance().isInitialized()) {
+        return ACE_INTERNAL_ERROR;
+    }
+    popup_func = handler;
+    // Changed order of checks to make API run with old popup implementation
+    // instead of always needing the popup handler to be implemented.
+    if (NULL == handler) {
+        LogError("NULL argument(s) passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_client_shutdown(void)
+{
+    popup_func = NULL;
+    return ACE_OK;
+}
+
+ace_return_t ace_check_access_ex(const ace_request_t* request, ace_check_result_t* result)
+{
+    if (NULL == request || NULL == result) {
+        LogError("NULL argument(s) passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+
+    AceClient::AceRequest aceRequest;
+    aceRequest.sessionId = request->session_id;
+    aceRequest.widgetHandle = request->widget_handle;
+
+    aceRequest.apiFeatures.count = request->feature_list.count;
+    aceRequest.apiFeatures.apiFeature =
+            const_cast<const char**>(request->feature_list.items);
+    aceRequest.functionName = NULL; // TODO will  be removed
+    aceRequest.deviceCapabilities.devcapsCount = request->dev_cap_list.count;
+    aceRequest.deviceCapabilities.paramsCount = request->dev_cap_list.count;
+
+    char** devCapNames = new char*[request->dev_cap_list.count];
+    AceClient::AceParamList* paramList =
+            new AceClient::AceParamList[request->dev_cap_list.count];
+
+    unsigned int i;
+    for (i = 0; i < request->dev_cap_list.count; ++i) {
+        devCapNames[i] = request->dev_cap_list.items[i].name;
+        paramList[i].count = request->dev_cap_list.items[i].param_list.count;
+
+        paramList[i].param = new AceClient::AceParam[
+                               request->dev_cap_list.items[i].param_list.count];
+
+        unsigned int j;
+        for (j = 0; j < request->dev_cap_list.items[i].param_list.count; ++j) {
+            paramList[i].param[j].name =
+                    request->dev_cap_list.items[i].param_list.items[j].name;
+            paramList[i].param[j].value =
+                    request->dev_cap_list.items[i].param_list.items[j].value;
+
+        }
+    }
+
+    aceRequest.deviceCapabilities.devCapNames =
+            const_cast<const char**>(devCapNames);
+    aceRequest.deviceCapabilities.params = paramList;
+
+    bool ret = false;
+
+    Try {
+        ret = AceClient::AceThinClientSingleton::
+                Instance().checkFunctionCall(aceRequest);
+        *result = ret ? ACE_ACCESS_GRANTED : ACE_PRIVILEGE_DENIED;
+
+        if (*result == ACE_ACCESS_GRANTED) {
+            ret = AceClient::AceThinClientSingleton::
+                Instance().checkPrivacy(aceRequest);
+            *result = ret ? ACE_ACCESS_GRANTED : ACE_PRIVACY_DENIED;
+        }
+    } Catch (AceClient::AceThinClient::Exception::AceThinClientException) {
+        LogError("Ace client exception");
+        delete [] devCapNames;
+        for (i = 0; i < request->dev_cap_list.count; ++i) {
+            delete [] paramList[i].param;
+        }
+        delete [] paramList;
+        return ACE_INTERNAL_ERROR;
+    }
+
+    delete [] devCapNames;
+    for (i = 0; i < request->dev_cap_list.count; ++i) {
+        delete [] paramList[i].param;
+    }
+    delete [] paramList;
+    return ACE_OK;
+}
diff --git a/ace_client/src/ace_client.cpp b/ace_client/src/ace_client.cpp
new file mode 100644 (file)
index 0000000..7be8eeb
--- /dev/null
@@ -0,0 +1,703 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        ace_client.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of AceThinClient class
+ */
+
+#include <memory>
+#include <set>
+#include <map>
+
+#include <dpl/string.h>
+#include <dpl/optional_typedefs.h>
+#include <boost/optional.hpp>
+#include <dpl/log/log.h>
+#include <dpl/singleton_safe_impl.h>
+#include <ace-dao-ro/PromptModel.h>
+
+#include <ace_popup_handler.h>
+
+#include "ace_server_api.h"
+#include "popup_response_server_api.h"
+#include "ace-client/ace_client.h"
+#include "ace-client/ace_client_helper.h"
+#include <attribute_facade.h>
+#include <ace/Request.h>
+
+#include <app_manager.h>
+#include <package_manager.h>
+#include <privacy_checker_client.h>
+#include <unistd.h>
+#include <dpl/wrt-dao-ro/widget_dao_read_only.h>
+// ACE tests need to use mock implementations
+#ifdef ACE_CLIENT_TESTS
+
+#include "AceDAOReadOnly_mock.h"
+#include "communication_client_mock.h"
+#include "PolicyInformationPoint_mock.h"
+
+#else
+
+#include <ace-dao-ro/AceDAOReadOnly.h>
+#include "SecurityCommunicationClient.h"
+#include <ace/PolicyInformationPoint.h>
+
+#endif // ACE_CLIENT_TESTS
+
+IMPLEMENT_SAFE_SINGLETON(AceClient::AceThinClient)
+
+ace_popup_handler_func_t popup_func = NULL;
+
+namespace AceClient {
+
+namespace {
+// These devcaps actually are not requested in config file, so should be treaded
+// as if were requested (access tags/WARP will block request if desired)
+const std::string DEVCAP_EXTERNAL_NETWORK_ACCESS = "externalNetworkAccess";
+const std::string DEVCAP_XML_HTTP_REQUEST = "XMLHttpRequest";
+} // anonymous
+
+
+std::string AceFunctionParam::aceFunctionParamToken = "param:function";
+
+// popup cache result
+
+enum class AceCachedPromptResult {
+    PERMIT,
+    DENY,
+    ASK_POPUP
+};
+
+// AceThinClient implementation singleton
+class AceThinClientImpl {
+  public:
+    bool checkFunctionCall(const AceRequest& ace_request);
+    AcePreference getWidgetResourcePreference(
+            const AceResource& resource,
+            const AceWidgetHandle& handle) const;
+    bool checkPrivacy(const AceRequest& ace_request);
+    AceResourcesPreferences* getGlobalResourcesPreferences() const;
+    bool isInitialized() const;
+
+    AceThinClientImpl();
+    ~AceThinClientImpl();
+
+  protected:
+    bool containsNetworkDevCap(const AceRequest &ace_request);
+    bool checkFeatureList(const AceRequest& ace_request);
+    
+  private:
+    WebRuntimeImpl* m_wrt;
+    ResourceInformationImpl* m_res;
+    OperationSystemImpl* m_sys;
+    WrtSecurity::Communication::Client *m_communicationClient, *m_popupValidationClient;
+
+    AceSubject getSubjectForHandle(AceWidgetHandle handle) const;
+    AceCachedPromptResult getCachedPromptResult(
+            WidgetHandle widgetHandle,
+            int ruleId,
+            const AceSessionId& sessionId) const;
+    bool askUser(PolicyEffect popupType,
+                const AceRequest& ace_request,
+                const AceBasicRequest& request);
+    // Prompt validation
+    bool validatePopupResponse(
+                const AceRequest& ace_request,
+                const AceBasicRequest& request,
+                bool answer = true,
+                Prompt::Validity validity = Prompt::Validity::ALWAYS);
+    mutable PolicyInformationPoint m_pip;
+    boost::optional<std::set<DPL::String>> m_grantedDevCaps;
+    std::set<std::string> m_acceptedFeatures;
+};
+
+AceThinClientImpl::AceThinClientImpl()
+  : m_wrt(new WebRuntimeImpl()),
+    m_res(new ResourceInformationImpl()),
+    m_sys(new OperationSystemImpl()),
+    m_communicationClient(NULL),
+    m_popupValidationClient(NULL),
+    m_pip(m_wrt, m_res, m_sys)
+{
+    AceDB::AceDAOReadOnly::attachToThreadRO();
+    Try {
+        m_communicationClient = new WrtSecurity::Communication::Client(WrtSecurity::AceServerApi::INTERFACE_NAME());
+        m_popupValidationClient = new WrtSecurity::Communication::Client(WrtSecurity::PopupServerApi::INTERFACE_NAME());
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        if(m_communicationClient) delete m_communicationClient;
+        if(m_popupValidationClient) delete m_popupValidationClient;
+        delete m_wrt;
+        delete m_res;
+        delete m_sys;
+        ReThrowMsg(AceThinClient::Exception::AceThinClientException,
+                "Failed to call security daemon");
+    }
+}
+
+AceThinClientImpl::~AceThinClientImpl()
+{
+    Assert(NULL != m_communicationClient);
+    Assert(NULL != m_popupValidationClient);
+    delete m_communicationClient;
+    delete m_popupValidationClient;
+    delete m_wrt;
+    delete m_res;
+    delete m_sys;
+    m_communicationClient = NULL;
+    m_popupValidationClient = NULL;
+    AceDB::AceDAOReadOnly::detachFromThread();
+
+}
+
+bool AceThinClientImpl::isInitialized() const
+{
+    return NULL != m_communicationClient && NULL != m_popupValidationClient;
+}
+
+bool AceThinClientImpl::containsNetworkDevCap(const AceRequest &ace_request)
+{
+    AceDeviceCap deviceCap = ace_request.deviceCapabilities;
+    for (size_t j=0; j<deviceCap.devcapsCount; ++j) {
+        if (!deviceCap.devCapNames[j]) {
+            continue;
+        }
+        if (DEVCAP_XML_HTTP_REQUEST == deviceCap.devCapNames[j]
+            || DEVCAP_EXTERNAL_NETWORK_ACCESS == deviceCap.devCapNames[j])
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+bool AceThinClientImpl::checkFeatureList(const AceRequest& ace_request)
+{
+    for (size_t i=0; i<ace_request.apiFeatures.count; ++i) {
+        Assert(ace_request.apiFeatures.apiFeature[i]);
+        std::string featureName(ace_request.apiFeatures.apiFeature[i]);
+        LogInfo("Api feature: " << featureName);
+        if (0 != m_acceptedFeatures.count(featureName)) {
+            return true;
+        }
+        LogInfo("Api-feature was not requested in widget config: " <<
+          featureName);
+    }
+    return false;
+}
+
+bool AceThinClientImpl::checkPrivacy(const AceRequest& ace_request)
+{
+    int res;
+
+    WrtDB::WidgetDAOReadOnly dao(ace_request.widgetHandle);
+    std::string tzPkgId = DPL::ToUTF8String(dao.getTizenPkgId());
+
+    LogInfo("Checking pkg_id : " << tzPkgId.c_str());
+
+    for (size_t i = 0; i < ace_request.apiFeatures.count; ++i) {
+        res = privacy_checker_check_package_by_privilege(tzPkgId.c_str(), ace_request.apiFeatures.apiFeature[i]);
+        LogInfo(" privilege : " << ace_request.apiFeatures.apiFeature[i] << " : " << ((res == PRIV_MGR_ERROR_SUCCESS) ? "true" : "false"));
+        if (res != PRIV_MGR_ERROR_SUCCESS)
+            return false;
+    }
+
+    return true;
+}
+
+bool AceThinClientImpl::checkFunctionCall(const AceRequest& ace_request)
+{
+    LogInfo("Enter");
+
+    // fill the m_grantedDevCaps, if not yet initialized
+    // TODO: This is not so pretty. AceThinClient is not explicitly
+    // tied to a widget handle, yet we assume it is always used
+    // with the same handle. This will be amended in a future
+    // refactoring (already planned).
+    if (!m_grantedDevCaps) {
+        m_grantedDevCaps = std::set<DPL::String>();
+        m_acceptedFeatures.clear();
+
+        AceDB::FeatureNameVector fvector;
+        Try {
+            AceDB::AceDAOReadOnly::getAcceptedFeature(ace_request.widgetHandle, &fvector);
+        } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+            LogError("Failed to read DB");
+            return false;
+        }
+        for(size_t i=0; i<fvector.size(); ++i) {
+            m_acceptedFeatures.insert(DPL::ToUTF8String(fvector[i]));
+         }
+    }
+
+    AceSubject subject = getSubjectForHandle(ace_request.widgetHandle);
+
+    // Create function params
+    const AceDeviceCap& devcaps = ace_request.deviceCapabilities;
+
+    LogInfo("Checking against config requested api-features.");
+
+    // Network device caps are not connected with api-features.
+    // We must pass empty api-feature when network dev cap is set.
+    if (!containsNetworkDevCap(ace_request) && !checkFeatureList(ace_request)) {
+        return false;
+    }
+
+    AceFunctionParams functionParams(devcaps.devcapsCount);
+    for (size_t i = 0; i < devcaps.devcapsCount; ++i) {
+        AceFunctionParam functionParam;
+        functionParam.addAttribute(AceFunctionParam::aceFunctionParamToken,
+                                   NULL == ace_request.functionName ?
+                                   "" : ace_request.functionName);
+        if (devcaps.paramsCount) {
+            Assert(devcaps.params);
+            for (size_t j = 0; j < devcaps.params[i].count; ++j) {
+                Assert(devcaps.params[i].param &&
+                       devcaps.params[i].param[j].name &&
+                       devcaps.params[i].param[j].value);
+                functionParam.addAttribute(
+                    std::string(devcaps.params[i].param[j].name),
+                    std::string(devcaps.params[i].param[j].value));
+            }
+        }
+        functionParams.push_back(functionParam);
+    }
+
+    // Convert AceRequest to array of AceBasicRequests
+    AceBasicRequests requests;
+
+    for (size_t i = 0; i < devcaps.devcapsCount; ++i) {
+        // Adding dev cap name here as resource id
+        Assert(devcaps.devCapNames[i]);
+        LogInfo("Device cap: " << devcaps.devCapNames[i]);
+        AceBasicRequest request(subject,
+                                devcaps.devCapNames[i],
+                                functionParams[i]);
+        requests.push_back(request);
+    }
+
+    // true means access granted, false - denied
+    bool result = true;
+
+    FOREACH(it, requests){
+        // Getting attributes from ACE DAO
+        AceBasicRequest& request = *it;
+        AceDB::BaseAttributeSet attributeSet;
+        AceDB::AceDAOReadOnly::getAttributes(&attributeSet);
+
+        // If true, we need to make popup IPC and ask user for decision
+        bool askPopup = false;
+        // If true, we need to make IPC to security daemon for policy
+        // decision on granting access
+        bool askServer = false;
+        // If askPopup == true, this is the kind of popup to  be opened
+        PolicyEffect popupType = PolicyEffect::PROMPT_ONESHOT;
+
+        if (attributeSet.empty()) {
+            // Treat this case as missed cache - ask security daemon
+            LogInfo("Empty attribute set");
+            askServer = true;
+        } else {
+            // Filling attributes with proper values
+            FunctionParamImpl params;
+            AceParamKeys keys = request.getFunctionParam().getKeys();
+            AceParamValues values = request.getFunctionParam().getValues();
+            for (size_t i = 0; i < keys.size(); ++i) {
+                params.addAttribute(keys[i], values[i]);
+            }
+            Request req(ace_request.widgetHandle,
+                        WidgetExecutionPhase_Invoke,
+                        &params);
+            req.addDeviceCapability(request.getResourceId());
+
+            m_pip.getAttributesValues(&req, &attributeSet);
+
+            // Getting cached policy result
+            OptionalExtendedPolicyResult exPolicyResult =
+                    AceDB::AceDAOReadOnly::getPolicyResult(attributeSet);
+
+            if (!exPolicyResult) {
+                // Missed cache - ask security daemon
+                LogInfo("Missed policy result cache");
+                askServer = true;
+            } else {
+                // Cached value found - now interpret it
+                LogInfo("Result in cache");
+                OptionalPolicyEffect effect = exPolicyResult->policyResult.getEffect();
+                if (!effect) {
+                    // PolicyDecision is UNDETERMINED or NOT_APPLICABLE
+                    result = false;
+                    break;
+                } else if (*effect == PolicyEffect::DENY) {
+                    // Access denied
+                    result = false;
+                    break;
+                } else if (*effect == PolicyEffect::PERMIT) {
+                    // Access granted
+                    if (m_grantedDevCaps->find(
+                           DPL::FromASCIIString(request.getResourceId()))
+                        != m_grantedDevCaps->end())
+                    {
+                        continue;
+                    } else
+                        askServer = true;
+                } else {
+                    // Check for cached popup response
+                    LogInfo("Checking cached popup response");
+                    AceCachedPromptResult promptCached =
+                     getCachedPromptResult(ace_request.widgetHandle,
+                                           exPolicyResult->ruleId,
+                                           ace_request.sessionId);
+                    if (promptCached == AceCachedPromptResult::PERMIT) {
+                        // Granted by previous popup
+                        LogDebug("Cache found OK");
+                        if (m_grantedDevCaps->find(
+                               DPL::FromASCIIString(request.getResourceId()))
+                            != m_grantedDevCaps->end())
+                        {
+                            LogDebug("SMACK given previously");
+                            continue;
+                        } else {
+                            if (*effect != PolicyEffect::PROMPT_BLANKET) {
+                                // This should not happen.
+                                LogDebug("This should not happen.");
+                                result = false;
+                                break;
+                            }
+                            if (!validatePopupResponse(ace_request,
+                                                             request)) {
+                                LogDebug("Daemon has not validated response.");
+                                result = false;
+                                break;
+                            } else {
+                                // Access granted, move on to next request
+                                LogDebug("SMACK granted, all OK");
+                                m_grantedDevCaps->insert(
+                                    DPL::FromASCIIString(
+                                            request.getResourceId()));
+                                continue;
+                            }
+                        }
+                    }
+                    if (promptCached == AceCachedPromptResult::DENY) {
+                        // Access denied by earlier popup
+                        result = false;
+                        break;
+                    }
+                    if (promptCached == AceCachedPromptResult::ASK_POPUP) {
+                        askPopup = true;
+                        popupType = *effect;
+                    }
+                }
+            }
+        }
+
+        if (askServer) {
+            // IPC to security daemon
+            // here we must check if we have a SMACK permission for
+            // the device cap requested
+            LogInfo("Asking security daemon");
+            int serializedPolicyResult = 0;
+            Try {
+                m_communicationClient->call(WrtSecurity::AceServerApi::CHECK_ACCESS_METHOD(),
+                                   ace_request.widgetHandle,
+                                   request.getSubjectId(),
+                                   request.getResourceId(),
+                                   request.getFunctionParam().getKeys(),
+                                   request.getFunctionParam().getValues(),
+                                   ace_request.sessionId,
+                                   &serializedPolicyResult);
+            } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+                ReThrowMsg(AceThinClient::Exception::AceThinClientException,
+                         "Failed to call security daemon");
+            }
+            PolicyResult policyResult = PolicyResult::
+                    deserialize(serializedPolicyResult);
+            OptionalPolicyEffect effect = policyResult.getEffect();
+            if (!effect) {
+                // PolicyDecision is UNDETERMINED or NOT_APPLICABLE
+                result = false;
+                break;
+            }
+            if (*effect == PolicyEffect::DENY) {
+                // Access denied
+                result = false;
+                break;
+            }
+            if (*effect == PolicyEffect::PERMIT) {
+                // Access granted, move on to next request
+                m_grantedDevCaps->insert(
+                    DPL::FromASCIIString(request.getResourceId()));
+
+                continue;
+            }
+            // Policy says: ask user - setup popup kind
+            popupType = *effect;
+            askPopup = true;
+        }
+
+        if (askPopup) {
+            result = askUser(popupType, ace_request, request);
+        }
+    }
+
+    LogInfo("Result: " << (result ? "GRANTED" : "DENIED"));
+    return result;
+}
+
+bool AceThinClientImpl::askUser(PolicyEffect popupType,
+                                const AceRequest& ace_request,
+                                const AceBasicRequest& request)
+{
+    LogInfo("Asking popup");
+    Assert(NULL != popup_func);
+
+    const AceFunctionParam& fParam = request.getFunctionParam();
+    AceParamKeys keys = fParam.getKeys();
+    AceParamValues values = fParam.getValues();
+
+    ace_popup_t ace_popup_type;
+    ace_resource_t resource = const_cast<ace_session_id_t>(
+            request.getResourceId().c_str());
+    ace_session_id_t session = const_cast<ace_session_id_t>(
+            ace_request.sessionId.c_str());;
+    ace_param_list_t parameters;
+    ace_widget_handle_t handle = ace_request.widgetHandle;
+
+    parameters.count = keys.size();
+    parameters.items = new ace_param_t[parameters.count];
+    unsigned int i;
+    for (i = 0; i < parameters.count; ++i) {
+        parameters.items[i].name =
+                const_cast<ace_string_t>(keys[i].c_str());
+        parameters.items[i].value =
+                const_cast<ace_string_t>(values[i].c_str());
+    }
+
+    switch (popupType) {
+    case PolicyEffect::PROMPT_ONESHOT: {
+        ace_popup_type = ACE_ONESHOT;
+        break; }
+    case PolicyEffect::PROMPT_SESSION: {
+        ace_popup_type = ACE_SESSION;
+        break; }
+    case PolicyEffect::PROMPT_BLANKET: {
+        ace_popup_type = ACE_BLANKET;
+        break; }
+    default: {
+        LogError("Unknown popup type passed!");
+        LogError("Maybe effect isn't a popup?");
+        LogError("Effect number is: " << static_cast<int>(popupType));
+        Assert(0); }
+    }
+
+    ace_bool_t answer = ACE_FALSE;
+    ace_return_t ret = popup_func(ace_popup_type,
+                    resource,
+                    session,
+                    &parameters,
+                    handle,
+                    &answer);
+
+    delete [] parameters.items;
+
+    if (ACE_OK != ret) {
+        LogError("Error in popup handler");
+        return false;
+    }
+
+    if (ACE_TRUE == answer) {
+        m_grantedDevCaps->insert(
+            DPL::FromASCIIString(request.getResourceId()));
+        return true;
+    }
+
+    return false;
+}
+
+bool AceThinClientImpl::validatePopupResponse(
+        const AceRequest& ace_request,
+        const AceBasicRequest& request,
+        bool answer,
+        Prompt::Validity validity
+        )
+{
+    bool response = false;
+    Try{
+        m_popupValidationClient->call(
+                           WrtSecurity::PopupServerApi::VALIDATION_METHOD(),
+                           answer,
+                           static_cast<int>(validity),
+                           ace_request.widgetHandle,
+                           request.getSubjectId(),
+                           request.getResourceId(),
+                           request.getFunctionParam().getKeys(),
+                           request.getFunctionParam().getValues(),
+                           ace_request.sessionId,
+                           &response);
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        ReThrowMsg(AceThinClient::Exception::AceThinClientException,
+                 "Failed to call security daemon");
+    }
+    return response;
+}
+
+AcePreference AceThinClientImpl::getWidgetResourcePreference (
+        const AceResource& resource,
+        const AceWidgetHandle& handle) const
+{
+    return toAcePreference(
+            AceDB::AceDAOReadOnly::getWidgetDevCapSetting(resource, handle));
+}
+
+AceResourcesPreferences* AceThinClientImpl::getGlobalResourcesPreferences()
+const
+{
+    AceDB::PreferenceTypesMap globalSettingsMap;
+    AceResourcesPreferences* acePreferences = new AceResourcesPreferences();
+    AceDB::AceDAOReadOnly::getDevCapSettings(&globalSettingsMap);
+    FOREACH(it, globalSettingsMap) {
+        acePreferences->insert(
+                AceResurcePreference((*it).first,
+                        toAcePreference((*it).second)));
+    }
+    return acePreferences;
+}
+
+AceSubject AceThinClientImpl::getSubjectForHandle(AceWidgetHandle handle) const
+{
+    try
+    {
+        return AceDB::AceDAOReadOnly::getGUID(handle);
+    }
+    catch (AceDB::AceDAOReadOnly::Exception::DatabaseError& /*ex*/)
+    {
+        LogError("Couldn't find GIUD for handle " << handle);
+        return "";
+    }
+}
+
+AceCachedPromptResult AceThinClientImpl::getCachedPromptResult(
+        WidgetHandle widgetHandle,
+        int ruleId,
+        const AceSessionId& sessionId) const
+{
+    OptionalCachedPromptDecision promptDecision =
+    AceDB::AceDAOReadOnly::getPromptDecision(
+            widgetHandle,
+            ruleId);
+    if (!promptDecision) {
+        LogDebug("No cache");
+        return AceCachedPromptResult::ASK_POPUP;
+    } else {
+        // These should not be stored in DB!
+        Assert(PromptDecision::ALLOW_THIS_TIME
+                != (*promptDecision).decision);
+        Assert(PromptDecision::DENY_THIS_TIME
+                != (*promptDecision).decision);
+        if ((*promptDecision).decision ==
+                PromptDecision::ALLOW_ALWAYS) {
+            // Access granted via earlier popup
+            LogDebug("ALLOW_ALWAYS");
+            return AceCachedPromptResult::PERMIT;
+        }
+        if ((*promptDecision).decision ==
+                PromptDecision::DENY_ALWAYS) {
+            LogDebug("DENY_ALWAYS");
+            // Access denied via earlier popup
+            return AceCachedPromptResult::DENY;
+        }
+        // Only thing left is per session prompts
+        if (!(*promptDecision).session) {
+            LogDebug("NO SESSION");
+            return AceCachedPromptResult::ASK_POPUP;
+        }
+        AceSessionId cachedSessionId = DPL::ToUTF8String(*((*promptDecision).session));
+        if ((*promptDecision).decision ==
+                PromptDecision::ALLOW_FOR_SESSION) {
+            if (cachedSessionId == sessionId) {
+                // Access granted for this session.
+                LogDebug("SESSION OK, PERMIT");
+                return AceCachedPromptResult::PERMIT;
+            } else {
+                LogDebug("SESSION NOT OK, ASKING");
+                return AceCachedPromptResult::ASK_POPUP;
+            }
+        }
+        if ((*promptDecision).decision ==
+                PromptDecision::DENY_FOR_SESSION) {
+            if (cachedSessionId == sessionId) {
+                // Access denied for this session.
+                LogDebug("SESSION OK, DENY");
+                return AceCachedPromptResult::DENY;
+            } else {
+                LogDebug("SESSION NOT OK, ASKING");
+                return AceCachedPromptResult::ASK_POPUP;
+            }
+        }
+    }
+    LogDebug("NO RESULT, ASKING");
+    return AceCachedPromptResult::ASK_POPUP;
+}
+
+// AceThinClient
+
+bool AceThinClient::checkFunctionCall(
+        const AceRequest& ace_request) const
+{
+    return m_impl->checkFunctionCall(ace_request);
+}
+
+bool AceThinClient::checkPrivacy(
+        const AceRequest& ace_request) const
+{
+    return m_impl->checkPrivacy(ace_request);
+}
+
+AcePreference AceThinClient::getWidgetResourcePreference(
+        const AceResource& resource,
+        const AceWidgetHandle& handle) const
+{
+    return m_impl->getWidgetResourcePreference(
+            resource, handle);
+}
+
+AceResourcesPreferences* AceThinClient::getGlobalResourcesPreferences()
+const
+{
+    return m_impl->getGlobalResourcesPreferences();
+}
+
+AceThinClient::AceThinClient()
+{
+    m_impl = new AceThinClientImpl();
+}
+
+AceThinClient::~AceThinClient()
+{
+    Assert(NULL != m_impl);
+    delete m_impl;
+}
+
+bool AceThinClient::isInitialized() const
+{
+    return NULL != m_impl && m_impl->isInitialized();
+}
+
+
+} // namespace AceClient
diff --git a/ace_client/src/example/CMakeLists.txt b/ace_client/src/example/CMakeLists.txt
new file mode 100644 (file)
index 0000000..b3e9259
--- /dev/null
@@ -0,0 +1,26 @@
+cmake_minimum_required(VERSION 2.6)
+project(ace-thin-client-example)
+
+include(FindPkgConfig)
+
+pkg_check_modules(DEPS
+                  dpl-efl
+                  REQUIRED)
+
+pkg_search_module(wrt-ace-client REQUIRED wrt-ace-client)
+
+set(TARGET_NAME "ace-thin-client-example")
+
+set(SRCS
+    ace-thin-client-example.cpp)
+
+include_directories(${DEPS_INCLUDE_DIRS})
+include_directories(${wrt-ace-client_INCLUDE_DIRS})
+
+add_definitions("-DDPL_LOGS_ENABLED")
+
+add_executable(${TARGET_NAME} ${SRCS})
+
+target_link_libraries(${TARGET_NAME}
+    ${DEPS_LDFLAGS}
+    ${wrt-ace-client_LDFLAGS})
diff --git a/ace_client/src/example/ace-thin-client-example.cpp b/ace_client/src/example/ace-thin-client-example.cpp
new file mode 100644 (file)
index 0000000..aa4c4a8
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace-thin-client-example.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       Example usage of ACE thin client.
+ */
+
+#include <ace_client.h>
+
+int main(int argc, char **argv)
+{
+    AceClient::AceThinClient& client =
+            AceClient::AceThinClientSingleton::Instance();
+    client.initialize(); // this fires echo method - see logs
+    client.deinitialize();
+    return 0;
+}
+
diff --git a/ace_common/CMakeLists.txt b/ace_common/CMakeLists.txt
new file mode 100644 (file)
index 0000000..7e7926a
--- /dev/null
@@ -0,0 +1,4 @@
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/ace_common/include/ace_api_common.h
+    DESTINATION include/ace-common
+    )
diff --git a/ace_common/include/ace_api_common.h b/ace_common/include/ace_api_common.h
new file mode 100644 (file)
index 0000000..b42d048
--- /dev/null
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_api_common.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This is header for basic ACE data types and error codes
+ */
+
+#ifndef ACE_API_COMMON_H
+#define ACE_API_COMMON_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// --------------- Boolean type and errors -------------------------------------
+
+/*
+ * Order and values of enum constants are part of API
+ */
+typedef enum
+{
+    ACE_FALSE,
+    ACE_TRUE
+} ace_bool_t;
+
+typedef enum
+{
+    ACE_ACCESS_GRANTED,
+    ACE_PRIVILEGE_DENIED,
+    ACE_PRIVACY_DENIED
+} ace_check_result_t;
+
+typedef enum
+{
+    ACE_OK,                 // Operation succeeded
+    ACE_INVALID_ARGUMENTS,  // Invalid input parameters
+    ACE_INTERNAL_ERROR,     // ACE internal error
+    ACE_ACE_UNKNOWN_ERROR   // Unexpected operation
+} ace_return_t;
+
+// --------------- Basic types -------------------------------------------------
+
+typedef size_t  ace_size_t;
+typedef char*   ace_string_t;           // NULL-terminated string
+typedef int     ace_widget_handle_t;
+typedef char*   ace_resource_t;
+typedef char*   ace_subject_t;
+typedef char*   ace_session_id_t;
+typedef void*   ace_private_data_t;
+
+// --------------- Access requests ---------------------------------------------
+
+typedef struct
+{
+    ace_size_t        count;
+    ace_string_t*     items;
+} ace_feature_list_t;
+
+typedef struct
+{
+    ace_string_t name;
+    ace_string_t value;
+} ace_param_t;
+
+typedef struct
+{
+    ace_size_t      count;
+    ace_param_t*    items;
+} ace_param_list_t;
+
+typedef struct
+{
+    ace_string_t     name;
+    ace_param_list_t param_list;
+} ace_dev_cap_t;
+
+typedef struct
+{
+    ace_size_t        count;
+    ace_dev_cap_t*    items;
+} ace_dev_cap_list_t;
+
+typedef struct
+{
+    ace_session_id_t    session_id;         // DEPRECATED will be removed
+    ace_widget_handle_t widget_handle;      // DEPRECATED will be removed
+    ace_feature_list_t  feature_list;
+    ace_dev_cap_list_t  dev_cap_list;
+} ace_request_t;
+
+// --------------- Popup data types --------------------------------------------
+
+/*
+ * Popup types that can be requested to be displayed by ACE
+ */
+typedef enum
+{
+    ACE_ONESHOT,
+    ACE_SESSION,
+    ACE_BLANKET
+} ace_popup_t;
+
+/*
+ * Validity of answer that can be returned by ACE popup
+ */
+typedef enum
+{
+    ACE_ONCE,
+    ACE_PER_SESSION,
+    ACE_ALWAYS
+} ace_validity_t;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_API_COMMON_H
diff --git a/ace_install/CMakeLists.txt b/ace_install/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4b7537b
--- /dev/null
@@ -0,0 +1 @@
+ADD_SUBDIRECTORY(src)
diff --git a/ace_install/include/ace_api_install.h b/ace_install/include/ace_api_install.h
new file mode 100644 (file)
index 0000000..734861c
--- /dev/null
@@ -0,0 +1,185 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_api_setup.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This is C api for Access Control Engine (ACE), installer mode
+ *              (RW part).
+ *
+ */
+
+#ifndef ACE_API_H
+#define ACE_API_H
+
+#include <ace_api_common.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * API defined in this header should be used only from one thread. If used
+ * otherwise, unexpected behaviour may occur, including segmentation faults and
+ * escalation of global warming. Be warned.
+ */
+
+// --------------- Initialization and policy update ----------------------------
+
+/*
+ * Initializes ACE - connects (RW) to the database. Must be called only once.
+ * Returns ACE_OK or error
+ */
+ace_return_t ace_install_initialize(void);
+
+/*
+ * Deinitializes ACE - deinitialize internal structures, detach DB, etc.
+ * Must be called only once.
+ * Returns ACE_OK or error
+ */
+ace_return_t ace_install_shutdown(void);
+
+/*
+ * Updates policy - parses XML files from known locations (reason for no arguments),
+ * also clears policy and prompt caches.
+ * Returns ACE_OK or error
+ */
+ace_return_t ace_update_policy(void);
+
+// --------------- Requested device capabilities API for installer -------------
+
+typedef struct
+{
+    ace_string_t   device_capability;
+    ace_bool_t     smack_granted;
+} ace_requested_dev_cap_t;
+
+typedef struct
+{
+    ace_size_t              count;
+    ace_requested_dev_cap_t*  items;
+} ace_requested_dev_cap_list_t;
+
+/*
+ * Deletes data allocated by ace_get_requested_dev_caps - a helper function
+ */
+ace_return_t ace_free_requested_dev_caps(ace_requested_dev_cap_list_t* caps);
+
+/*
+ * Returns ACE_OK or error; 'caps' will hold device capabilities information.
+ * To free allcated resources in 'caps', use ace_free_requested_dev_caps
+ */
+ace_return_t ace_get_requested_dev_caps(ace_widget_handle_t handle,
+                                        ace_requested_dev_cap_list_t* caps);
+
+/*
+ * Returns error or ACE_OK
+ */
+ace_return_t ace_set_requested_dev_caps(ace_widget_handle_t handle,
+                                        const ace_requested_dev_cap_list_t* caps);
+
+ace_return_t ace_rem_requested_dev_caps(ace_widget_handle_t handle);
+
+// ---------------- Accepted Api featuresk API for installer ----------------
+
+
+ace_return_t ace_set_accepted_feature(ace_widget_handle_t handle,
+                                      const ace_feature_list_t* flist);
+
+ace_return_t ace_rem_accepted_feature(ace_widget_handle_t handle);
+
+// --------------- Widget data setup for installation --------------------------
+
+typedef enum
+{
+    WAC20 = 0,
+    Tizen
+} ace_widget_type_t;
+
+struct widget_info {
+    ace_widget_type_t type;
+    ace_string_t id;
+    ace_string_t version;
+    ace_string_t author;
+    ace_string_t shareHerf;
+};
+
+typedef enum
+{
+    AUTHOR,
+    DISTRIBUTOR,
+    UNKNOWN
+} ace_cert_owner_t;
+
+typedef enum
+{
+    ROOT,
+    ENDENTITY
+} ace_cert_type_t;
+
+typedef struct certificate_data {
+    ace_cert_owner_t owner;
+    ace_cert_type_t type;
+    int chain_id;
+    ace_string_t md5_fp;
+    ace_string_t sha1_fp;
+    ace_string_t common_name;
+} ace_certificate_data;
+
+/*
+ * Register widget info into database.
+ * @param cert_data NULL terminated list of widget certificates
+ */
+
+ace_return_t ace_register_widget(ace_widget_handle_t handle,
+                                 struct widget_info* info,
+                                 ace_certificate_data* cert_data[]);
+
+ace_return_t ace_unregister_widget(ace_widget_handle_t handle);
+
+ace_return_t ace_is_widget_installed(ace_widget_handle_t handle, bool *installed);
+
+/*
+ * Gets widget type in 'type'. Use in installer to determine which policy will be used
+ * by ACE for this widget.
+ * Returns error or ACE_OK
+ */
+ace_return_t ace_get_widget_type(ace_widget_handle_t handle,
+                                 ace_widget_type_t* type);
+
+// --------------- Installation time policy check ------------------------------
+
+typedef enum
+{
+    ACE_PERMIT,
+    ACE_DENY,
+    ACE_PROMPT,
+    ACE_UNDEFINED
+} ace_policy_result_t;
+
+/*
+ * Gets current policy evaluation for given device capability and given widget.
+ * Returns error or ACE_OK
+ */
+ace_return_t ace_get_policy_result(const ace_resource_t,
+                                   ace_widget_handle_t handle,
+                                   ace_policy_result_t* result);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_API_H
diff --git a/ace_install/src/CMakeLists.txt b/ace_install/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..2414b6c
--- /dev/null
@@ -0,0 +1,81 @@
+include(FindPkgConfig)
+
+IF(DEFINED DBUS_CONNECTION)
+PKG_CHECK_MODULES(ACE_INSTALL_DEPS
+    dpl-efl
+    dpl-dbus-efl
+    REQUIRED
+    )
+ENDIF()
+
+SET(ACE_INSTALL_DIR
+    ${PROJECT_SOURCE_DIR}/ace_install
+    )
+
+SET(ACE_INSTALL_SRC_DIR
+    ${ACE_INSTALL_DIR}/src
+    )
+
+SET(ACE_INSTALL_INCLUDE_DIR
+    ${ACE_INSTALL_DIR}/include
+    )
+
+SET(ACE_INSTALL_SOURCES
+    ${COMMUNICATION_CLIENT_SOURCES}
+    ${ACE_INSTALL_SRC_DIR}/ace_api_install.cpp    
+    )
+
+SET(ACE_INSTALL_INCLUDES
+    ${COMMUNICATION_CLIENT_INCLUDES}
+    ${ACE_INSTALL_DEPS_INCLUDE_DIRS}
+    ${ACE_INSTALL_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    ${PROJECT_SOURCE_DIR}/ace/include
+    ${PROJECT_SOURCE_DIR}/src/services/ace
+    ${PROJECT_SOURCE_DIR}/src/services/ace/dbus/api
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus
+    )
+
+ADD_DEFINITIONS(${ACE_INSTALL_DEPS_CFLAGS})
+ADD_DEFINITIONS(${ACE_INSTALL_CFLAGS_OTHER})
+
+INCLUDE_DIRECTORIES(${ACE_INSTALL_INCLUDES})
+IF(NOT DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    )
+ENDIF()
+
+ADD_LIBRARY(${TARGET_ACE_INSTALL_LIB} SHARED ${ACE_INSTALL_SOURCES})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_INSTALL_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_INSTALL_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+IF(DEFINED DBUS_CONNECTION)
+TARGET_LINK_LIBRARIES(${TARGET_ACE_INSTALL_LIB}
+    ${ACE_INSTALL_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RW_LIB}
+    )
+ELSE()
+TARGET_LINK_LIBRARIES(${TARGET_ACE_INSTALL_LIB}
+    ${ACE_INSTALL_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RW_LIB}
+    libwrt-security-commons
+    libwrt-security-commons-log
+    )
+ENDIF()
+
+INSTALL(TARGETS ${TARGET_ACE_INSTALL_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+    ${ACE_INSTALL_INCLUDE_DIR}/ace_api_install.h
+    DESTINATION include/ace-install
+    )
diff --git a/ace_install/src/ace_api_install.cpp b/ace_install/src/ace_api_install.cpp
new file mode 100644 (file)
index 0000000..a18d452
--- /dev/null
@@ -0,0 +1,357 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        ace_api_install.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation ACE installator API
+ */
+
+#include <string>
+#include <utility>
+#include <string.h>
+#include <dpl/log/log.h>
+#include <dpl/foreach.h>
+#include <dpl/string.h>
+#include "SecurityCommunicationClient.h"
+#include <ace-dao-rw/AceDAO.h>
+#include "ace_server_api.h"
+
+#include "ace_api_install.h"
+
+static WrtSecurity::Communication::Client *communicationClient = NULL;
+
+// helper functions
+
+static AceDB::AppTypes to_db_app_type(ace_widget_type_t widget_type)
+{
+    switch (widget_type) {
+    case WAC20:
+        return AceDB::AppTypes::WAC20;
+    case Tizen:
+        return AceDB::AppTypes::Tizen;
+    default:
+        return AceDB::AppTypes::Unknown;
+    }
+}
+
+static ace_widget_type_t to_ace_widget_type(AceDB::AppTypes app_type)
+{
+    switch (app_type) {
+    case AceDB::AppTypes::WAC20:
+        return WAC20;
+    case AceDB::AppTypes::Tizen:
+        return Tizen;
+    default:
+        LogError("Invalid app type for widget");
+        return WAC20;
+    }
+}
+
+ace_return_t ace_install_initialize(void)
+{
+    if (NULL != communicationClient) {
+        LogError("ace_api_install already initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    AceDB::AceDAO::attachToThreadRW();
+    Try {
+        communicationClient = new WrtSecurity::Communication::Client(
+                   WrtSecurity::AceServerApi::INTERFACE_NAME());
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Can't connect to daemon");
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_install_shutdown(void)
+{
+    if (NULL == communicationClient) {
+        LogError("ace_api_install not initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    delete communicationClient;
+    communicationClient = NULL;
+    AceDB::AceDAO::detachFromThread();
+    return ACE_OK;
+}
+
+ace_return_t ace_update_policy(void)
+{
+    Try {
+        communicationClient->call(WrtSecurity::AceServerApi::UPDATE_POLICY_METHOD());
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Problem with connection to daemon");
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_free_requested_dev_caps(ace_requested_dev_cap_list_t* caps)
+{
+    if (NULL == caps || NULL == caps->items) {
+        LogError("Invalid arguments");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    unsigned int i;
+    for (i = 0; i < caps->count; ++i) {
+        delete [] caps->items[i].device_capability;
+    }
+    delete [] caps->items;
+    return ACE_OK;
+}
+
+ace_return_t ace_get_requested_dev_caps(ace_widget_handle_t handle,
+                                        ace_requested_dev_cap_list_t* caps)
+{
+    if (NULL == caps) {
+        LogError("Invalid arguments");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    AceDB::RequestedDevCapsMap permissions;
+    Try {
+        AceDB::AceDAO::getRequestedDevCaps(
+                handle, &permissions);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    caps->items = new ace_requested_dev_cap_t[permissions.size()];
+    caps->count = permissions.size();
+    unsigned int i = 0;
+    FOREACH (it, permissions) {
+        std::string devCapRequested = DPL::ToUTF8String(it->first);
+        int length = strlen(devCapRequested.c_str());
+        caps->items[i].device_capability =
+                new char[length + 1];
+        memset(caps->items[i].device_capability, 0, length + 1);
+        strncpy(caps->items[i].device_capability, devCapRequested.c_str(), length);
+        caps->items[i].smack_granted = it->second ? ACE_TRUE : ACE_FALSE;
+        ++i;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_set_requested_dev_caps(
+        ace_widget_handle_t handle,
+        const ace_requested_dev_cap_list_t* caps)
+{
+    if (NULL == caps) {
+        LogError("Invalid arguments");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    AceDB::RequestedDevCapsMap db_permissions;
+    unsigned int i;
+    for (i = 0; i < caps->count; ++i) {
+        std::string devCap = std::string(caps->items[i].device_capability);
+        db_permissions.insert(std::make_pair(DPL::FromUTF8String(devCap),
+                              caps->items[i].smack_granted == ACE_TRUE));
+    }
+    Try {
+        AceDB::AceDAO::setRequestedDevCaps(
+                handle, db_permissions);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+ace_return_t ace_rem_requested_dev_caps(
+        ace_widget_handle_t handle)
+{
+    Try {
+        AceDB::AceDAO::removeRequestedDevCaps(handle);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_set_accepted_feature(
+        ace_widget_handle_t handle,
+        const ace_feature_list_t *feature)
+{
+    if (NULL == feature) {
+        LogError("Invalid argument");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    AceDB::FeatureNameVector fvector;
+    ace_size_t i;
+    for (i = 0; i < feature->count; ++i) {
+        fvector.push_back(
+            DPL::FromUTF8String(feature->items[i]));
+    }
+    Try {
+        AceDB::AceDAO::setAcceptedFeature(handle, fvector);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_rem_accepted_feature(
+        ace_widget_handle_t handle)
+{
+    Try {
+        AceDB::AceDAO::removeAcceptedFeature(handle);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_register_widget(ace_widget_handle_t handle,
+                                 struct widget_info *info,
+                                 ace_certificate_data* cert_data[])
+{
+    LogDebug("enter");
+
+    if (NULL == info || AceDB::AceDAOReadOnly::isWidgetInstalled(handle))
+        return ACE_INVALID_ARGUMENTS;
+
+    AceDB::WidgetRegisterInfo wri;
+    wri.type = to_db_app_type(info->type);
+
+    if (info->id)
+        wri.widget_id = DPL::FromUTF8String(info->id);
+    if (info->version)
+        wri.version = DPL::FromUTF8String(info->version);
+    if (info->author)
+        wri.authorName = DPL::FromUTF8String(info->author);
+    if (info->shareHerf)
+        wri.shareHref = DPL::FromUTF8String(info->shareHerf);
+
+    AceDB::WidgetCertificateDataList dataList;
+    if (NULL != cert_data) {
+        AceDB::WidgetCertificateData wcd;
+        ace_certificate_data* cd;
+        int i = 0;
+        while (cert_data[i] != NULL)
+        {
+            cd = cert_data[i++]; //increment
+            switch(cd->type) {
+            case ROOT:
+                wcd.type = AceDB::WidgetCertificateData::Type::ROOT;
+                break;
+            case ENDENTITY:
+                wcd.type = AceDB::WidgetCertificateData::Type::ENDENTITY;
+                break;
+            }
+            switch(cd->owner) {
+            case AUTHOR:
+                wcd.owner = AceDB::WidgetCertificateData::Owner::AUTHOR;
+                break;
+            case DISTRIBUTOR:
+                wcd.owner = AceDB::WidgetCertificateData::Owner::DISTRIBUTOR;
+                break;
+            case UNKNOWN: default:
+                wcd.owner = AceDB::WidgetCertificateData::Owner::UNKNOWN;
+                break;
+            }
+            wcd.chainId = cd->chain_id;
+            if (cd->md5_fp)
+                wcd.strMD5Fingerprint = cd->md5_fp;
+            if (cd->sha1_fp)
+                wcd.strSHA1Fingerprint = cd->sha1_fp;
+            if (cd->common_name)
+                wcd.strCommonName = DPL::FromUTF8String(cd->common_name);
+            dataList.push_back(wcd);
+        }
+        LogDebug("All data set. Inserting into database.");
+    }
+
+    Try {
+        AceDB::AceDAO::registerWidgetInfo((WidgetHandle)(handle), wri, dataList);
+        LogDebug("AceDB entry done");
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_unregister_widget(ace_widget_handle_t handle)
+{
+    Try {
+        AceDB::AceDAO::unregisterWidgetInfo((WidgetHandle)(handle));
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_is_widget_installed(ace_widget_handle_t handle, bool *installed)
+{
+    Try {
+        *installed = AceDB::AceDAO::isWidgetInstalled((WidgetHandle)(handle));
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_get_widget_type(ace_widget_handle_t handle,
+                                 ace_widget_type_t* type)
+{
+    if (NULL == type) {
+        LogError("Invalid arguments");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    Try {
+        AceDB::AppTypes db_type = AceDB::AceDAO::getWidgetType(handle);
+        *type = to_ace_widget_type(db_type);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_get_policy_result(const ace_resource_t resource,
+                                   ace_widget_handle_t handle,
+                                   ace_policy_result_t* result)
+{
+    if (NULL == result) {
+        LogError("Invalid arguments");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    int serializedPolicyResult = 0;
+    Try {
+       std::string resource_str(resource);
+       communicationClient->call(WrtSecurity::AceServerApi::CHECK_ACCESS_INSTALL_METHOD(),
+                        handle,
+                        resource_str,
+                        &serializedPolicyResult);
+   } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+       LogError("Can't connect to daemon");
+       return ACE_INTERNAL_ERROR;
+   }
+   PolicyResult policyResult = PolicyResult::
+           deserialize(serializedPolicyResult);
+   OptionalPolicyEffect effect = policyResult.getEffect();
+   if (!effect) {
+       *result = ACE_UNDEFINED;
+   } else if (*effect == PolicyEffect::DENY) {
+       *result = ACE_DENY;
+   } else if (*effect == PolicyEffect::PERMIT) {
+       *result = ACE_PERMIT;
+   } else if (*effect == PolicyEffect::PROMPT_ONESHOT ||
+              *effect == PolicyEffect::PROMPT_BLANKET ||
+              *effect == PolicyEffect::PROMPT_SESSION){
+       *result = ACE_PROMPT;
+   } else {
+       *result = ACE_UNDEFINED;
+   }
+
+   return ACE_OK;
+}
diff --git a/ace_popup_validation/CMakeLists.txt b/ace_popup_validation/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4b7537b
--- /dev/null
@@ -0,0 +1 @@
+ADD_SUBDIRECTORY(src)
diff --git a/ace_popup_validation/include/ace_api_popup_validation.h b/ace_popup_validation/include/ace_api_popup_validation.h
new file mode 100644 (file)
index 0000000..f06dfcf
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_popup_validation_api.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This is C api for Access Control Engine (ACE), popup
+ *              validation library.
+ *
+ */
+
+#ifndef ACE_API_H
+#define ACE_API_H
+
+#include <ace_api_common.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// --------------- Initialization and deinitialization -------------------------
+
+/*
+ * Initializes the library.
+ *
+ * Returns error or ACE_OK.
+ */
+ace_return_t ace_popup_validation_initialize(void);
+
+/*
+ * Deinitializes the library.
+ *
+ * Returns error or ACE_OK.
+ */
+ace_return_t ace_popup_validation_shutdown(void);
+
+// --------------- Popup answer validation API ---------------------------------
+
+/*
+ * Validation of popup answer. This API must be called by implementation of
+ * UI handler. The call must be made from safe process, specially labelled by
+ * SMACK. If returned value is ACE_OK, 'validation_result' holds validation
+ * result that needs to be passed by UI handler as validation result. Otherwise
+ * value of 'validation_result' is undefined.
+ *
+ * See header ace_api_client.h for more details on where this function needs to
+ * be called and what arguments need to be passed here.
+ *
+ * Returns error or ACE_OK.
+ */
+ace_return_t ace_validate_answer(ace_bool_t answer,
+                                 ace_validity_t validity,
+                                 const ace_resource_t resource_name,
+                                 const ace_session_id_t session_id,
+                                 const ace_param_list_t* param_list,
+                                 ace_widget_handle_t handle,
+                                 ace_bool_t* validation_result);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_API_H
diff --git a/ace_popup_validation/src/CMakeLists.txt b/ace_popup_validation/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..5811176
--- /dev/null
@@ -0,0 +1,81 @@
+include(FindPkgConfig)
+
+IF(DEFINED DBUS_CONNECTION)
+PKG_CHECK_MODULES(ACE_POPUP_VALIDATION_DEPS
+    dpl-efl
+    dpl-dbus-efl
+    REQUIRED
+    )
+ENDIF()
+
+SET(ACE_POPUP_VALIDATION_DIR
+    ${PROJECT_SOURCE_DIR}/ace_popup_validation
+    )
+
+SET(ACE_POPUP_VALIDATION_SRC_DIR
+    ${ACE_POPUP_VALIDATION_DIR}/src
+    )
+
+SET(ACE_POPUP_VALIDATION_INCLUDE_DIR
+    ${ACE_POPUP_VALIDATION_DIR}/include
+    )
+
+SET(ACE_POPUP_VALIDATION_SOURCES
+    ${COMMUNICATION_CLIENT_SOURCES}
+    ${ACE_POPUP_VALIDATION_SRC_DIR}/ace_api_popup_validation.cpp    
+    )
+
+SET(ACE_POPUP_VALIDATION_INCLUDES
+    ${COMMUNICATION_CLIENT_INCLUDES}
+    ${ACE_POPUP_VALIDATION_DEPS_INCLUDE_DIRS}
+    ${ACE_POPUP_VALIDATION_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    ${PROJECT_SOURCE_DIR}/ace/include
+    ${PROJECT_SOURCE_DIR}/src/services/ace/dbus/api        
+    ${PROJECT_SOURCE_DIR}/src/services/ace
+    ${PROJECT_SOURCE_DIR}/src/services/popup/
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus    
+    )
+
+ADD_DEFINITIONS(${ACE_POPUP_VALIDATION_DEPS_CFLAGS})
+ADD_DEFINITIONS(${ACE_POPUP_VALIDATION_CFLAGS_OTHER})
+
+INCLUDE_DIRECTORIES(${ACE_POPUP_VALIDATION_INCLUDES})
+IF(NOT DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    )
+ENDIF()
+ADD_LIBRARY(${TARGET_ACE_POPUP_VALIDATION_LIB} SHARED ${ACE_POPUP_VALIDATION_SOURCES})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_POPUP_VALIDATION_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_POPUP_VALIDATION_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+IF(DEFINED DBUS_CONNECTION)
+TARGET_LINK_LIBRARIES(${TARGET_ACE_POPUP_VALIDATION_LIB}
+    ${ACE_POPUP_VALIDATION_DEPS_LIBRARIES} 
+    ${ACE_POPUP_VALIDATION_DEPS_LDFLAGS}
+    )
+ELSE()
+TARGET_LINK_LIBRARIES(${TARGET_ACE_POPUP_VALIDATION_LIB}
+    ${ACE_POPUP_VALIDATION_DEPS_LIBRARIES} 
+    ${ACE_POPUP_VALIDATION_DEPS_LDFLAGS}
+    libwrt-security-commons
+    libwrt-security-commons-log
+    )
+ENDIF()
+
+INSTALL(TARGETS ${TARGET_ACE_POPUP_VALIDATION_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+    ${ACE_POPUP_VALIDATION_INCLUDE_DIR}/ace_api_popup_validation.h
+    DESTINATION include/ace-popup-validation
+    )
diff --git a/ace_popup_validation/src/ace_api_popup_validation.cpp b/ace_popup_validation/src/ace_api_popup_validation.cpp
new file mode 100644 (file)
index 0000000..32e8b13
--- /dev/null
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        ace_api_popup_validation.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of ACE popup validation API.
+ */
+
+#include <string>
+#include <vector>
+#include <dpl/log/log.h>
+#include "SecurityCommunicationClient.h"
+#include "popup_response_server_api.h"
+#ifdef DBUS_CONNECTION
+#include "security_daemon_dbus_config.h"
+#endif
+#include "ace_api_popup_validation.h"
+
+namespace {
+static WrtSecurity::Communication::Client *communicationClient = NULL;
+static const int VALIDITY_ONCE_VALUE = 0;
+static const int VALIDITY_SESSION_VALUE = 1;
+static const int VALIDITY_ALWAYS_VALUE = 1;
+} // anonymous
+
+ace_return_t ace_popup_validation_initialize(void)
+{
+    if (NULL != communicationClient) {
+        LogError("ace_api_popup_validation already initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    Try {
+        communicationClient = new WrtSecurity::Communication::Client(
+                   WrtSecurity::PopupServerApi::INTERFACE_NAME());
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Can't connect to daemon");
+        return ACE_INTERNAL_ERROR;
+    }
+
+    return ACE_OK; 
+}
+
+ace_return_t ace_popup_validation_shutdown(void)
+{
+    if (NULL == communicationClient) {
+        LogError("ace_api_popup_validation not initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    delete communicationClient;
+    communicationClient = NULL;
+
+    return ACE_OK;
+}
+
+ace_return_t ace_validate_answer(ace_bool_t answer,
+                                 ace_validity_t validity,
+                                 const ace_resource_t resource_name,
+                                 const ace_session_id_t session_id,
+                                 const ace_param_list_t* param_list,
+                                 ace_widget_handle_t handle,
+                                 ace_bool_t* validation_result)
+{
+    if (NULL == resource_name ||
+        NULL == session_id ||
+        NULL == param_list ||
+        NULL == validation_result)
+    {
+        LogError("NULL argument(s) passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+
+    bool dbusAnswer = answer == ACE_TRUE;
+    int dbusValidity = 0;
+
+    switch (validity) {
+    case ACE_ONCE: {
+        dbusValidity = VALIDITY_ONCE_VALUE;
+        //static_cast<int>(Prompt::Validity::ONCE);
+        break; }
+    case ACE_SESSION: {
+        dbusValidity = VALIDITY_SESSION_VALUE;
+        //static_cast<int>(Prompt::Validity::SESSION);
+        break; }
+    case ACE_ALWAYS: {
+        dbusValidity = VALIDITY_ALWAYS_VALUE;
+        //static_cast<int>(Prompt::Validity::ALWAYS);
+        break; }
+    default: {
+        LogError("Invalid validity passed");
+        return ACE_INVALID_ARGUMENTS; }
+    }
+
+    std::string subjectId;
+    std::string resourceId(resource_name);
+    std::string sessionId(session_id);
+    std::vector<std::string> keys, values;
+    unsigned int i;
+    for (i = 0; i < param_list->count; ++i) {
+        keys.push_back(std::string(param_list->items[i].name));
+        values.push_back(std::string(param_list->items[i].value));
+    }
+
+    bool response = false;
+    Try{
+        communicationClient->call(WrtSecurity::PopupServerApi::VALIDATION_METHOD(),
+                         dbusAnswer,
+                         dbusValidity,
+                         handle,
+                         subjectId,
+                         resourceId,
+                         keys,
+                         values,
+                         sessionId,
+                         &response);
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Can't call daemon");
+        return ACE_INTERNAL_ERROR;
+    }
+
+    *validation_result = response ? ACE_TRUE : ACE_FALSE;
+
+    return ACE_OK;
+}
diff --git a/ace_settings/CMakeLists.txt b/ace_settings/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4b7537b
--- /dev/null
@@ -0,0 +1 @@
+ADD_SUBDIRECTORY(src)
diff --git a/ace_settings/include/ace_api_settings.h b/ace_settings/include/ace_api_settings.h
new file mode 100644 (file)
index 0000000..a3c72ab
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_api_settings.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This is header for ACE settings API (RW part).
+ */
+
+#ifndef ACE_API_SETTINGS_H
+#define ACE_API_SETTINGS_H
+
+#include <ace_api_common.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * API defined in this header should be used only from one thread. If used
+ * otherwise, unexpected behaviour may occur, including segmentation faults and
+ * escalation of global warming. Be warned.
+ */
+
+// --------------- Initialization ----------------------------------------------
+
+/*
+ * Initializes ACE - connects (RW) to the database. Must be called only once.
+ * Returns ACE_OK or error
+ */
+ace_return_t ace_settings_initialize(void);
+
+/*
+ * Deinitializes ACE - deinitialize internal structures, detach DB, etc.
+ * Must be called only once.
+ * Returns ACE_OK or error
+ */
+ace_return_t ace_settings_shutdown(void);
+
+// --------------- Resource settings API ---------------------------------------
+
+/*
+ * Order and values of enum constants are part of API
+ */
+typedef enum
+{
+    ACE_PREFERENCE_PERMIT,
+    ACE_PREFERENCE_DENY,
+    ACE_PREFERENCE_DEFAULT,         // means: not set
+    ACE_PREFERENCE_BLANKET_PROMPT,
+    ACE_PREFERENCE_SESSION_PROMPT,
+    ACE_PREFERENCE_ONE_SHOT_PROMPT
+} ace_preference_t;
+
+/*
+ * Returns error or ACE_OK
+ * If return value is ACE_OK, 'prerefence' value is the queried one, otherwise
+ * 'preference' value is undefined
+ */
+ace_return_t ace_get_widget_resource_preference(ace_widget_handle_t handle,
+                                                const ace_resource_t resource,
+                                                ace_preference_t* preference);
+
+/*
+ * Returns error or ACE_OK
+ * If return value is ACE_OK, 'prerefence' value is the queried one, otherwise
+ * 'preference' value is undefined
+ */
+ace_return_t ace_get_global_resource_preference(const ace_resource_t resource,
+        ace_preference_t* preference);
+
+/*
+ * To reset setting, pass ACE_PREFERENCE_DEFAULT
+ * Returns error or ACE_OK
+ */
+ace_return_t ace_set_widget_resource_preference(ace_widget_handle_t handle,
+                                                const ace_resource_t resource,
+                                                ace_preference_t preference);
+
+/*
+ * To reset setting, pass ACE_PREFERENCE_DEFAULT
+ * Returns error or ACE_OK
+ */
+ace_return_t ace_set_global_resource_preference(const ace_resource_t resource,
+                                                ace_preference_t preference);
+
+/*
+ * Resets per widget resource settings to ACE_PREFERENCE_DEFAULT
+ */
+ace_return_t ace_reset_widget_resource_settings(void);
+
+/*
+ * Resets global resource settings to ACE_PREFERENCE_DEFAULT
+ */
+ace_return_t ace_reset_global_resource_settings(void);
+
+/*
+ * After execution, is_privacy_api is ACE_TRUE if resource_name is the name
+ * of Privacy API
+ */
+ace_return_t ace_is_private_api(const ace_resource_t resource_name,
+                       ace_bool_t* is_private_api);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_API_SETTINGS_H
diff --git a/ace_settings/src/CMakeLists.txt b/ace_settings/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..e4d527d
--- /dev/null
@@ -0,0 +1,75 @@
+include(FindPkgConfig)
+
+IF(DEFINED DBUS_CONNECTION)
+PKG_CHECK_MODULES(ACE_SETTINGS_DEPS
+    dpl-efl
+    REQUIRED
+    )
+ENDIF()
+
+SET(ACE_SETTINGS_DIR
+    ${PROJECT_SOURCE_DIR}/ace_settings
+    )
+
+SET(ACE_SETTINGS_SRC_DIR
+    ${ACE_SETTINGS_DIR}/src
+    )
+
+SET(ACE_SETTINGS_INCLUDE_DIR
+    ${ACE_SETTINGS_DIR}/include
+    )
+
+SET(ACE_SETTINGS_SOURCES
+    ${ACE_SETTINGS_SRC_DIR}/ace_api_settings.cpp    
+    )
+
+SET(ACE_SETTINGS_INCLUDES
+    ${ACE_SETTINGS_DEPS_INCLUDE_DIRS}
+    ${ACE_SETTINGS_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    ${PROJECT_SOURCE_DIR}/ace/include
+    )
+
+ADD_DEFINITIONS(${ACE_SETTINGS_DEPS_CFLAGS})
+ADD_DEFINITIONS(${ACE_SETTINGS_CFLAGS_OTHER})
+
+INCLUDE_DIRECTORIES(${ACE_SETTINGS_INCLUDES})
+IF(NOT DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    )
+ENDIF()
+
+ADD_LIBRARY(${TARGET_ACE_SETTINGS_LIB} SHARED ${ACE_SETTINGS_SOURCES})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_SETTINGS_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_SETTINGS_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+IF(DEFINED DBUS_CONNECTION)
+TARGET_LINK_LIBRARIES(${TARGET_ACE_SETTINGS_LIB}
+    ${ACE_SETTINGS_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RW_LIB}
+    )
+ELSE()
+TARGET_LINK_LIBRARIES(${TARGET_ACE_SETTINGS_LIB}
+    ${ACE_SETTINGS_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RW_LIB}
+    wrt-security-commons
+    wrt-security-commons-log
+    )
+ENDIF()
+
+INSTALL(TARGETS ${TARGET_ACE_SETTINGS_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+    ${ACE_SETTINGS_INCLUDE_DIR}/ace_api_settings.h
+    DESTINATION include/ace-settings
+    )
diff --git a/ace_settings/src/ace_api_settings.cpp b/ace_settings/src/ace_api_settings.cpp
new file mode 100644 (file)
index 0000000..a1a811d
--- /dev/null
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        ace_api_settings.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation ACE settings API
+ */
+
+#include <string>
+#include <dpl/log/log.h>
+#include <ace-dao-rw/AceDAO.h>
+
+#include "ace_api_settings.h"
+
+// helper functions
+static ace_preference_t to_ace_preference(const AceDB::PreferenceTypes& db_preference)
+{
+    switch (db_preference) {
+    case AceDB::PreferenceTypes::PREFERENCE_BLANKET_PROMPT: {
+        return ACE_PREFERENCE_BLANKET_PROMPT; }
+    case AceDB::PreferenceTypes::PREFERENCE_DEFAULT: {
+        return ACE_PREFERENCE_DEFAULT;}
+    case AceDB::PreferenceTypes::PREFERENCE_DENY: {
+        return ACE_PREFERENCE_DENY;}
+    case AceDB::PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT: {
+        return ACE_PREFERENCE_ONE_SHOT_PROMPT;}
+    case AceDB::PreferenceTypes::PREFERENCE_PERMIT: {
+        return ACE_PREFERENCE_PERMIT;}
+    case AceDB::PreferenceTypes::PREFERENCE_SESSION_PROMPT: {
+        return ACE_PREFERENCE_SESSION_PROMPT;}
+    default: {
+        return ACE_PREFERENCE_DEFAULT;}
+    }
+}
+
+
+static AceDB::PreferenceTypes to_ace_db_preference(const ace_preference_t& preference)
+{
+    switch (preference) {
+    case ACE_PREFERENCE_BLANKET_PROMPT: {
+        return AceDB::PreferenceTypes::PREFERENCE_BLANKET_PROMPT; }
+    case ACE_PREFERENCE_DEFAULT: {
+        return AceDB::PreferenceTypes::PREFERENCE_DEFAULT;}
+    case ACE_PREFERENCE_DENY: {
+        return AceDB::PreferenceTypes::PREFERENCE_DENY;}
+    case ACE_PREFERENCE_ONE_SHOT_PROMPT: {
+        return AceDB::PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT;}
+    case ACE_PREFERENCE_PERMIT: {
+        return AceDB::PreferenceTypes::PREFERENCE_PERMIT;}
+    case ACE_PREFERENCE_SESSION_PROMPT: {
+        return AceDB::PreferenceTypes::PREFERENCE_SESSION_PROMPT;}
+    default: {
+        return AceDB::PreferenceTypes::PREFERENCE_DEFAULT;}
+    }
+}
+
+ace_return_t ace_settings_initialize(void)
+{
+    AceDB::AceDAO::attachToThreadRW();
+    return ACE_OK;
+}
+
+ace_return_t ace_settings_shutdown(void)
+{
+    AceDB::AceDAO::detachFromThread();
+    return ACE_OK;
+}
+
+ace_return_t ace_get_widget_resource_preference(ace_widget_handle_t handle,
+                                                const ace_resource_t resource,
+                                                ace_preference_t* preference)
+{
+    if (NULL == resource || NULL == preference) {
+        LogError("NULL argument(s) passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    Try {
+        std::string resource_str(resource);
+        AceDB::PreferenceTypes db_preference =
+                AceDB::AceDAO::getWidgetDevCapSetting(resource_str, handle);
+        *preference = to_ace_preference(db_preference);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_get_global_resource_preference(const ace_resource_t resource,
+                                                ace_preference_t* preference)
+{
+    if (NULL == resource || NULL == preference) {
+        LogError("NULL argument(s) passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    Try {
+        AceDB::PreferenceTypes db_preference =
+                AceDB::AceDAO::getDevCapSetting(resource);
+        *preference = to_ace_preference(db_preference);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_set_widget_resource_preference(ace_widget_handle_t handle,
+                                                const ace_resource_t resource,
+                                                ace_preference_t preference)
+{
+    if (NULL == resource) {
+        LogError("NULL argument passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    Try {
+        AceDB::AceDAO::addResource(resource);
+        AceDB::PreferenceTypes db_preference = to_ace_db_preference(preference);
+        AceDB::AceDAO::removeWidgetDevCapSetting(resource, handle);
+        AceDB::AceDAO::setWidgetDevCapSetting(resource, handle, db_preference);
+    } Catch(AceDB::AceDAO::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_set_global_resource_preference(const ace_resource_t resource,
+                                                ace_preference_t preference)
+{
+    if (NULL == resource) {
+        LogError("NULL argument passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    Try {
+        AceDB::AceDAO::addResource(resource);
+        AceDB::PreferenceTypes db_preference = to_ace_db_preference(preference);
+        AceDB::AceDAO::setDevCapSetting(resource, db_preference);
+    } Catch(AceDB::AceDAO::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_reset_widget_resource_settings()
+{
+    Try {
+        AceDB::AceDAO::clearWidgetDevCapSettings();
+    } Catch(AceDB::AceDAO::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_reset_global_resource_settings(void)
+{
+    Try {
+        AceDB::AceDAO::clearDevCapSettings();
+    } Catch(AceDB::AceDAO::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_is_private_api(const ace_resource_t resource_name, ace_bool_t* is_private_api)
+{
+    static const char * const private_api[] = {
+        "bluetooth.admin",
+        "bluetooth.gap",
+        "bluetooth.spp",
+        "calendar.read",
+        "calendar.write",
+        "callhistory.read",
+        "callhistory.write",
+        "contact.read",
+        "contact.write",
+        "nfc.admin",
+        "nfc.common",
+        "nfc.cardemulation",
+        "nfc.p2p",
+        "nfc.tag",
+        NULL
+    };
+
+    *is_private_api = ACE_TRUE;
+    for (int i=0; private_api[i]; ++i)
+        if (!strcmp(resource_name, private_api[i]))
+            return ACE_OK;
+
+    *is_private_api = ACE_FALSE;
+    return ACE_OK;
+}
+
diff --git a/build/CMakeLists.txt b/build/CMakeLists.txt
new file mode 100644 (file)
index 0000000..35766cc
--- /dev/null
@@ -0,0 +1,27 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+#
+ADD_SUBDIRECTORY(ace)
+ADD_SUBDIRECTORY(ace_client)
+ADD_SUBDIRECTORY(ace_settings)
+ADD_SUBDIRECTORY(ace_install)
+ADD_SUBDIRECTORY(ace_popup_validation)
+ADD_SUBDIRECTORY(communication_client)
+ADD_SUBDIRECTORY(wrt-security)
+IF(ENABLE_WRT_OCSP EQUAL 1)
+ADD_SUBDIRECTORY(wrt_ocsp)
+ENDIF()
diff --git a/build/ace/CMakeLists.txt b/build/ace/CMakeLists.txt
new file mode 100644 (file)
index 0000000..a6b2c58
--- /dev/null
@@ -0,0 +1,31 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-dao-ro.pc.in security-dao-ro.pc @ONLY)
+CONFIGURE_FILE(security-dao-rw.pc.in security-dao-rw.pc @ONLY)
+CONFIGURE_FILE(security.pc.in security.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/ace/security-dao-ro.pc
+    ${CMAKE_BINARY_DIR}/build/ace/security-dao-rw.pc
+    ${CMAKE_BINARY_DIR}/build/ace/security.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+  
diff --git a/build/ace/security-dao-ro.pc.in b/build/ace/security-dao-ro.pc.in
new file mode 100644 (file)
index 0000000..98c237a
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace-dao-ro
+Description: ace-dao-ro
+Version: @VERSION@
+Requires: dpl-efl openssl
+Libs: -lace-dao-ro -L${libdir}
+Cflags: -I${includedir}
diff --git a/build/ace/security-dao-rw.pc.in b/build/ace/security-dao-rw.pc.in
new file mode 100644 (file)
index 0000000..64ff12e
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: aco-dao-rw
+Description: ace-dao-rw
+Version: @VERSION@
+Requires: security-dao-ro
+Libs: -lace-dao-rw -L${libdir}
+Cflags: -I${includedir}
diff --git a/build/ace/security.pc.in b/build/ace/security.pc.in
new file mode 100644 (file)
index 0000000..366066a
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace
+Description: ace
+Version: @VERSION@
+Requires: dpl-efl openssl
+Libs: -lace -L${libdir}
+Cflags: -I${includedir}
diff --git a/build/ace_client/CMakeLists.txt b/build/ace_client/CMakeLists.txt
new file mode 100644 (file)
index 0000000..8f74532
--- /dev/null
@@ -0,0 +1,26 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-client.pc.in security-client.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/ace_client/security-client.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+  
diff --git a/build/ace_client/security-client.pc.in b/build/ace_client/security-client.pc.in
new file mode 100644 (file)
index 0000000..804dc6d
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace-client
+Description: ACE thin client library
+Version: @VERSION@
+Requires: dpl-wrt-dao-ro dpl-efl dpl-event-efl dpl-dbus-efl security-dao-ro
+Libs: -lace-client -L${libdir}
+Cflags: -I${includedir}/ace-client -I${includedir}/ace-common
diff --git a/build/ace_install/CMakeLists.txt b/build/ace_install/CMakeLists.txt
new file mode 100644 (file)
index 0000000..c9266b3
--- /dev/null
@@ -0,0 +1,26 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-install.pc.in security-install.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/ace_install/security-install.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+  
diff --git a/build/ace_install/security-install.pc.in b/build/ace_install/security-install.pc.in
new file mode 100644 (file)
index 0000000..5c41da5
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace-install
+Description: ACE insall library to be used by installer
+Version: @VERSION@
+Requires: dpl-efl dpl-dbus-efl security-dao-rw
+Libs: -lace-install -L${libdir}
+Cflags: -I${includedir}/ace-install -I${includedir}/ace-common
diff --git a/build/ace_popup_validation/CMakeLists.txt b/build/ace_popup_validation/CMakeLists.txt
new file mode 100644 (file)
index 0000000..720ea06
--- /dev/null
@@ -0,0 +1,26 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-popup-validation.pc.in security-popup-validation.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/ace_popup_validation/security-popup-validation.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+  
diff --git a/build/ace_popup_validation/security-popup-validation.pc.in b/build/ace_popup_validation/security-popup-validation.pc.in
new file mode 100644 (file)
index 0000000..fc1e7ab
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace-popup-validation
+Description: ACE popup validation library
+Version: @VERSION@
+Requires: dpl-efl dpl-dbus-efl
+Libs: -lace-popup-validation -L${libdir}
+Cflags: -I${includedir}/ace-popup-validation -I${includedir}/ace-common
diff --git a/build/ace_settings/CMakeLists.txt b/build/ace_settings/CMakeLists.txt
new file mode 100644 (file)
index 0000000..1830467
--- /dev/null
@@ -0,0 +1,26 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-settings.pc.in security-settings.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/ace_settings/security-settings.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+  
diff --git a/build/ace_settings/security-settings.pc.in b/build/ace_settings/security-settings.pc.in
new file mode 100644 (file)
index 0000000..aab9f6f
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace-settings
+Description: ACE settings library
+Version: @VERSION@
+Requires:
+Libs: -lace-settings -lace-dao-rw -L${libdir}
+Cflags: -I${includedir}/ace-settings -I${includedir}/ace-common
diff --git a/build/communication_client/CMakeLists.txt b/build/communication_client/CMakeLists.txt
new file mode 100644 (file)
index 0000000..8942a30
--- /dev/null
@@ -0,0 +1,26 @@
+# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Zofia Abramowska (z.abramowska@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-communication-client.pc.in security-communication-client.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/communication_client/security-communication-client.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+
diff --git a/build/communication_client/security-communication-client.pc.in b/build/communication_client/security-communication-client.pc.in
new file mode 100644 (file)
index 0000000..b86a4a4
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: communication-client
+Description: Security communication client library
+Version: @VERSION@
+Requires: dpl-efl dpl-dbus-efl
+Libs: -lcommunication-client  -L${libdir}
+Cflags: -I${includedir}/communication-client
diff --git a/build/wrt-security/CMakeLists.txt b/build/wrt-security/CMakeLists.txt
new file mode 100644 (file)
index 0000000..3ac02e1
--- /dev/null
@@ -0,0 +1,19 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+#
+CONFIGURE_FILE(security-core.pc.in security-core.pc @ONLY)
+INSTALL(FILES ${CMAKE_BINARY_DIR}/build/wrt-security/security-core.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig)
diff --git a/build/wrt-security/security-core.pc.in b/build/wrt-security/security-core.pc.in
new file mode 100644 (file)
index 0000000..e99ba9e
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include/wrt-security
+
+Name: wrt-security
+Description: wrt-security
+Version: @VERSION@
+Requires: dpl-efl dpl-wrt-dao-rw dpl-dbus-efl
+Libs: -L${libdir} -ldpl-dbus-efl
+Cflags: -I${includedir}
diff --git a/build/wrt_ocsp/CMakeLists.txt b/build/wrt_ocsp/CMakeLists.txt
new file mode 100644 (file)
index 0000000..ab11f72
--- /dev/null
@@ -0,0 +1,26 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Zofia Abramowska (z.abramowska@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-wrt-ocsp.pc.in security-wrt-ocsp.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/wrt_ocsp/security-wrt-ocsp.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+
diff --git a/build/wrt_ocsp/security-wrt-ocsp.pc.in b/build/wrt_ocsp/security-wrt-ocsp.pc.in
new file mode 100644 (file)
index 0000000..e965e8e
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: wrt-ocsp
+Description: WRT OCSP library to be used by wrt-client
+Version: @VERSION@
+Requires: dpl-efl dpl-dbus-efl
+Libs: -lwrt-ocsp -L${libdir}
+Cflags: -I${includedir}/wrt-ocsp
diff --git a/commons/CMakeLists.txt b/commons/CMakeLists.txt
new file mode 100644 (file)
index 0000000..a345c4e
--- /dev/null
@@ -0,0 +1,126 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+#
+# @file        CMakeLists.txt
+# @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+# @version     1.0
+# @brief
+#
+
+# Check minimum CMake version
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+
+# Project name
+PROJECT(wrt-security-commons)
+
+STRING(REGEX MATCH "([^.]*)" API_VERSION "${VERSION}")
+ADD_DEFINITIONS("-DAPI_VERSION=\"$(API_VERSION)\"")
+
+# Comment this to disable control of global settings with environment variable
+ADD_DEFINITIONS("-DGLOBAL_SETTINGS_CONTROL")
+
+# Build type
+IF(NOT CMAKE_BUILD_TYPE)
+    SET(CMAKE_BUILD_TYPE "Release")
+ENDIF(NOT CMAKE_BUILD_TYPE)
+
+# Options
+OPTION(DPL_LOG "DPL logs status" OFF)
+IF(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling")
+    MESSAGE(STATUS "Logging enabled for DPL")
+    ADD_DEFINITIONS("-DDPL_LOGS_ENABLED")
+ELSE(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling")
+    MESSAGE(STATUS "Logging disabled for DPL")
+ENDIF(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling")
+
+OPTION(WITH_TESTS "Build tests" OFF)
+OPTION(WITH_CHILD "Build additional test subdirectory. WITH_TEST must be ON" OFF)
+
+# Compiler flags
+SET(CMAKE_C_FLAGS_PROFILING    "-O2")
+SET(CMAKE_CXX_FLAGS_PROFILING  "-O2 -std=c++0x")
+SET(CMAKE_C_FLAGS_DEBUG        "-O0 -g")
+SET(CMAKE_CXX_FLAGS_DEBUG      "-O0 -std=c++0x -g")
+SET(CMAKE_C_FLAGS_RELEASE      "-O2 -g")
+SET(CMAKE_CXX_FLAGS_RELEASE    "-O2 -std=c++0x -g -fvisibility-inlines-hidden")
+SET(CMAKE_CXX_FLAGS_CCOV       "-O0 -std=c++0x -g --coverage")
+
+ADD_DEFINITIONS("-fPIC")                        # If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table. This option makes a difference on the m68k, PowerPC and SPARC. (BJ: our ARM too?)
+
+# Compiler flags
+ADD_DEFINITIONS("-fvisibility=default")         # mark all exported symbols as visible
+
+# Warnings mode
+#ADD_DEFINITIONS("-Werror")                      # Make all warnings into errors.
+
+# Warning flags
+ADD_DEFINITIONS("-Wall")                        # Generate all warnings
+ADD_DEFINITIONS("-Wextra")                      # Generate even more extra warnings
+ADD_DEFINITIONS("-pedantic")                    # Accept only pedantic code
+#ADD_DEFINITIONS("-Weffc++")                     # Accept only effective C++ code
+ADD_DEFINITIONS("-Wwrite-strings")              # Do not accept writing to contant string memory
+ADD_DEFINITIONS("-Winit-self")                  # Do not accept initializing variable with itself
+ADD_DEFINITIONS("-Wcast-align")                 # Do not accept misaligning with casting
+ADD_DEFINITIONS("-Wcast-qual")                  # Do not accept removing qualifiers with casting
+#ADD_DEFINITIONS("-Wold-style-cast")             # Do not accept old style casting
+ADD_DEFINITIONS("-Wpointer-arith")              # Warn about void pointer arthimetic
+ADD_DEFINITIONS("-Wstrict-aliasing")            # Ensure strict aliasing
+ADD_DEFINITIONS("-Wuninitialized")              # Do not accept uninitialized variables
+ADD_DEFINITIONS("-Wmissing-declarations")       # Warn about global and non-accesible functions
+ADD_DEFINITIONS("-Woverloaded-virtual")         # Warn about incidental overiding non-virtual base methods
+ADD_DEFINITIONS("-Wnon-virtual-dtor")           # Warn about non-virtual destructor
+ADD_DEFINITIONS("-Wctor-dtor-privacy")          # Warn about useless and non-constructible classes
+#ADD_DEFINITIONS("-Wlong-long")                  # Do not allow using long long
+#ADD_DEFINITIONS("-Wunreachable-code")           # Warn about unreachable code
+ADD_DEFINITIONS("-Wfloat-equal")                # Do not accept comparing floating points with equal operator
+ADD_DEFINITIONS("-Wabi")                        # Warn about possible ABI problems
+ADD_DEFINITIONS("-Wswitch-enum")                # Check switch enumeration
+ADD_DEFINITIONS("-Wformat=2")                   # Check printf formatting
+ADD_DEFINITIONS("-Wundef")                      # Warn if an undefined identifier is evaluated in an @if directive.
+ADD_DEFINITIONS("-Wshadow")                     # Warn whenever a local variable shadows another local variable, parameter or global variable or whenever a built-in function is shadowed
+ADD_DEFINITIONS("-Wconversion")                 # Warn for implicit conversions that may alter a value
+ADD_DEFINITIONS("-Wlogical-op")                 # Warn about suspicious uses of logical operators in expressions
+#ADD_DEFINITIONS("-Waggregate-return")           # Warn if any functions that return structures or unions are defined or called.
+ADD_DEFINITIONS("-Wmissing-field-initializers") # Warn if a structure's initializer has some fields missing.
+ADD_DEFINITIONS("-Wredundant-decls")            # Warn if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing.
+#ADD_DEFINITIONS("-Wmissing-include-dirs")       # Warn if a user-supplied include directory does not exist.
+ADD_DEFINITIONS("-Wswitch-default")             # Warn whenever a switch statement does not have a default case.
+ADD_DEFINITIONS("-Wsync-nand")                  # Warn when __sync_fetch_and_nand and __sync_nand_and_fetch built-in functions are used. These functions changed semantics in GCC 4.4.
+ADD_DEFINITIONS("-Wunused")                     # All the above -Wunused options combined.
+ADD_DEFINITIONS("-Wstrict-overflow=5")          # Also warn about cases where the compiler reduces the magnitude of a constant involved in a comparison.
+ADD_DEFINITIONS("-Wdisabled-optimization")      # Warn if a requested optimization pass is disabled.
+ADD_DEFINITIONS("-std=c++0x")
+
+#
+# Core library files
+#
+# Define all core library headers and sources. As detail files
+# are usually templated and though recompiled in each file, we
+# have to compile full source for each target.
+#
+
+# Set names of binaries being created
+SET(TARGET_DPL_EFL "lib${PROJECT_NAME}")
+SET(TARGET_DPL_DB_EFL "lib${PROJECT_NAME}-db")
+SET(TARGET_DPL_LOG_EFL "lib${PROJECT_NAME}-log")
+
+macro(configure_and_install_pkg PKG_FILE)
+    CONFIGURE_FILE(${PKG_FILE}.in ${PKG_FILE} @ONLY)
+    INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PKG_FILE} DESTINATION lib/pkgconfig)
+endmacro(configure_and_install_pkg)
+
+ADD_SUBDIRECTORY(modules)
+ADD_SUBDIRECTORY(build)
+
diff --git a/commons/LICENSE b/commons/LICENSE
new file mode 100644 (file)
index 0000000..247c97d
--- /dev/null
@@ -0,0 +1,203 @@
+Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/commons/NOTICE b/commons/NOTICE
new file mode 100644 (file)
index 0000000..ded3804
--- /dev/null
@@ -0,0 +1 @@
+Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
\ No newline at end of file
diff --git a/commons/build/CMakeLists.txt b/commons/build/CMakeLists.txt
new file mode 100644 (file)
index 0000000..cf24bfa
--- /dev/null
@@ -0,0 +1,23 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+MESSAGE("*****************************************compiling for commons*********************************")
+ADD_SUBDIRECTORY(core)
+ADD_SUBDIRECTORY(log)
+ADD_SUBDIRECTORY(db)
diff --git a/commons/build/core/CMakeLists.txt b/commons/build/core/CMakeLists.txt
new file mode 100644 (file)
index 0000000..fa78765
--- /dev/null
@@ -0,0 +1,65 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+# @version     1.0
+# @brief
+#
+
+# Check required modules
+INCLUDE(FindPkgConfig)
+PKG_CHECK_MODULES(SYS_EFL
+  icu-uc
+  openssl
+  dlog
+#  minizip
+  REQUIRED
+)
+
+# Add core include directories
+INCLUDE_DIRECTORIES(
+    ${DPL_LOG_INCLUDE_DIR}
+    ${DPL_CORE_INCLUDE_DIR}
+)
+
+INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_INCLUDE_DIRS})
+
+LINK_DIRECTORIES(${SYS_EFL_LIBRARY_DIRS})
+
+# Base EFL based DPL library
+SET(DPL_EFL_LIBRARY "${PROJECT_NAME}")
+
+# Build shared library
+ADD_LIBRARY(${TARGET_DPL_EFL} SHARED
+    ${DPL_CORE_SOURCES}
+    ${DPL_LOG_SOURCES}
+)
+
+TARGET_LINK_LIBRARIES(${TARGET_DPL_EFL} ${SYS_EFL_LIBRARIES} "-lrt")
+
+# Target library properties
+SET_TARGET_PROPERTIES(${TARGET_DPL_EFL} PROPERTIES
+    SOVERSION ${API_VERSION} 
+ VERSION ${VERSION}
+    CLEAN_DIRECT_OUTPUT 1
+    OUTPUT_NAME ${DPL_EFL_LIBRARY})
+
+# Install libraries
+INSTALL(TARGETS ${TARGET_DPL_EFL}
+        DESTINATION ${LIB_INSTALL_DIR})
+
+
+# Install pkgconfig script
+configure_and_install_pkg(wrt-security-commons.pc)
diff --git a/commons/build/core/DESCRIPTION b/commons/build/core/DESCRIPTION
new file mode 100644 (file)
index 0000000..f7f1581
--- /dev/null
@@ -0,0 +1,2 @@
+!!!options!!! stop
+EFL support
diff --git a/commons/build/core/wrt-security-commons.pc.in b/commons/build/core/wrt-security-commons.pc.in
new file mode 100644 (file)
index 0000000..d3a7eba
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=/usr
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+includedir=${prefix}/include
+
+Name: wrt-security-commons
+Description: wrt-security-commons library
+Version: @VERSION@
+Requires: openssl dlog 
+Libs: -L${libdir} -lwrt-security-commons
+Cflags: -I${includedir}/wrt-security-commons
diff --git a/commons/build/db/CMakeLists.txt b/commons/build/db/CMakeLists.txt
new file mode 100644 (file)
index 0000000..40f3e38
--- /dev/null
@@ -0,0 +1,67 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+# Check required modules
+INCLUDE(FindPkgConfig)
+PKG_CHECK_MODULES(SYS_EFL_DB
+    sqlite3
+    db-util
+    REQUIRED)
+
+# Add core include directories
+INCLUDE_DIRECTORIES(
+    ${DPL_LOG_INCLUDE_DIR}
+    ${DPL_CORE_INCLUDE_DIR}
+    ${DPL_DB_INCLUDE_DIR}
+)
+
+INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_INCLUDE_DIRS})
+INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_DB_INCLUDE_DIRS})
+
+LINK_DIRECTORIES(
+    ${SYS_EFL_DB_LIBRARY_DIRS}
+)
+
+# Base EFL based DPL library
+SET(DPL_EFL_DB_LIBRARY "${PROJECT_NAME}-db")
+
+# Build shared library
+
+ADD_LIBRARY(${TARGET_DPL_DB_EFL} SHARED  ${DPL_DB_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_DPL_DB_EFL}
+    ${SYS_EFL_DB_LIBRARIES}
+    ${TARGET_DPL_EFL}
+)
+
+# Target library properties
+SET_TARGET_PROPERTIES(${TARGET_DPL_DB_EFL} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION}
+    CLEAN_DIRECT_OUTPUT 1
+    OUTPUT_NAME ${DPL_EFL_DB_LIBRARY})
+
+# Install libraries
+INSTALL(TARGETS ${TARGET_DPL_DB_EFL}
+        DESTINATION ${LIB_INSTALL_DIR})
+#        DESTINATION lib)
+
+# Install pkgconfig script
+configure_and_install_pkg(wrt-security-commons-db.pc)
diff --git a/commons/build/db/wrt-security-commons-db.pc.in b/commons/build/db/wrt-security-commons-db.pc.in
new file mode 100644 (file)
index 0000000..5b0b8ee
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=/usr
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+includedir=${prefix}/include
+
+Name: wrt-security-commons-db
+Description: wrt security common library
+Version: @VERSION@
+Requires: wrt-security-commons sqlite3 db-util
+Libs: -L${libdir} -lwrt-security-commons
+Cflags: -I${includedir}/wrt-security-commons
diff --git a/commons/build/log/CMakeLists.txt b/commons/build/log/CMakeLists.txt
new file mode 100644 (file)
index 0000000..148f66e
--- /dev/null
@@ -0,0 +1,63 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+# Check required modules
+INCLUDE(FindPkgConfig)
+PKG_CHECK_MODULES(SYS_EFL_LOG
+    dlog
+    REQUIRED
+)
+
+# Add core include directories
+INCLUDE_DIRECTORIES(
+    ${DPL_LOG_INCLUDE_DIR}
+)
+
+INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_LOG_INCLUDE_DIRS})
+
+LINK_DIRECTORIES(
+    ${SYS_EFL_LOG_LIBRARY_DIRS}
+)
+
+# Base EFL based DPL library
+SET(DPL_EFL_LOG_LIBRARY "${PROJECT_NAME}-log")
+
+# Build shared library
+
+ADD_LIBRARY(${TARGET_DPL_LOG_EFL} SHARED  ${DPL_LOG_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_DPL_LOG_EFL}
+    ${SYS_EFL_LOG_LIBRARIES}
+)
+
+# Target library properties
+SET_TARGET_PROPERTIES(${TARGET_DPL_LOG_EFL} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION}
+    CLEAN_DIRECT_OUTPUT 1
+    OUTPUT_NAME ${DPL_EFL_LOG_LIBRARY})
+
+# Install libraries
+INSTALL(TARGETS ${TARGET_DPL_LOG_EFL}
+        DESTINATION ${LIB_INSTALL_DIR})
+#        DESTINATION lib)
+
+# Install pkgconfig script
+configure_and_install_pkg(wrt-security-commons-log.pc)
diff --git a/commons/build/log/wrt-security-commons-log.pc.in b/commons/build/log/wrt-security-commons-log.pc.in
new file mode 100644 (file)
index 0000000..7f18689
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=/usr
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+includedir=${prefix}/include
+
+Name: dpl-log-efl
+Description: DPL Log Engine - EFL based
+Version: @VERSION@
+Requires: dpl-efl dlog
+Libs: -L${libdir} -ldpl-log-efl
+Cflags: -I${includedir}/dpl-efl
diff --git a/commons/modules/CMakeLists.txt b/commons/modules/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4ee8728
--- /dev/null
@@ -0,0 +1,24 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+#
+# @file        CMakeLists.txt
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+include(core/config.cmake)
+include(log/config.cmake)
+include(db/config.cmake)
diff --git a/commons/modules/core/DESCRIPTION b/commons/modules/core/DESCRIPTION
new file mode 100644 (file)
index 0000000..1369c40
--- /dev/null
@@ -0,0 +1 @@
+Main library code
diff --git a/commons/modules/core/config.cmake b/commons/modules/core/config.cmake
new file mode 100644 (file)
index 0000000..038f3b7
--- /dev/null
@@ -0,0 +1,122 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+#
+# @file        config.cmake
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+# Set DPL core sources
+SET(DPL_CORE_SOURCES
+    ${PROJECT_SOURCE_DIR}/modules/core/src/assert.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/colors.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/errno_string.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/exception.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/mutex.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/noncopyable.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/recursive_mutex.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/serialization.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/single_instance.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/singleton.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/string.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/thread.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/waitable_event.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/waitable_handle.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/waitable_handle_watch_support.cpp
+    PARENT_SCOPE
+)
+
+
+# Set DPL core headers
+SET(DPL_CORE_HEADERS
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_input.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_input_output.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_output.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_input_adapter.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_input.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_input_output_adapter.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_input_output.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_output_adapter.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_output.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/address.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/aligned.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/apply.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/assert.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/atomic.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/availability.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/binary_queue.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/bind.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/bool_operator.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/char_traits.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/colors.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/copy.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/errno_string.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/exception.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/file_input.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/file_output.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/foreach.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/free_deleter.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/generic_event.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/lexical_cast.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/mutable_task_list.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/mutex.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/named_base_pipe.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/named_input_pipe.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/named_output_pipe.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/noncopyable.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/once.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/optional_typedefs.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/platform.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/preprocessor.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/read_write_mutex.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/recursive_mutex.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scope_guard.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scoped_resource.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scoped_close.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scoped_dir.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scoped_fclose.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scoped_free.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/serialization.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/semaphore.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/single_instance.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/singleton.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/singleton_impl.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/singleton_safe_impl.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/static_block.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/string.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/sstream.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/task.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/thread.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/type_list.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/union_cast.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/workaround.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/zip_input.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/application.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/framework_appcore.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/framework_efl.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/framework_vconf.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/main.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/waitable_event.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/waitable_handle.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/waitable_handle_watch_support.h
+    PARENT_SCOPE
+)
+
+SET(DPL_CORE_INCLUDE_DIR
+    ${PROJECT_SOURCE_DIR}/modules/core/include
+    PARENT_SCOPE
+)
+
diff --git a/commons/modules/core/include/DESCRIPTION b/commons/modules/core/include/DESCRIPTION
new file mode 100644 (file)
index 0000000..6dfd446
--- /dev/null
@@ -0,0 +1,2 @@
+!!!options!!! stop
+Header files, including template implementations
diff --git a/commons/modules/core/include/dpl/assert.h b/commons/modules/core/include/dpl/assert.h
new file mode 100644 (file)
index 0000000..abdb481
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        assert.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of assert
+ */
+#ifndef DPL_ASSERT_H
+#define DPL_ASSERT_H
+
+namespace DPL {
+// Assertion handler procedure
+// Do not call directly
+// Always use Assert macro
+void AssertProc(const char *condition,
+                const char *file,
+                int line,
+                const char *function) __attribute__ ((__noreturn__));
+} // namespace DPL
+
+#define Assert(Condition) do { if (!(Condition)) { DPL::AssertProc(#Condition, \
+                                                                   __FILE__, \
+                                                                   __LINE__, \
+                                                                   __FUNCTION__); \
+                               } } while (0)
+
+#define AssertMsg(Condition, Msg)                                         \
+    do {                                                                  \
+        if (!(Condition)) {                                               \
+            DPL::AssertProc(                                              \
+                (std::string(std::string(#Condition)+" ") + Msg).c_str(), \
+                __FILE__, __LINE__, __FUNCTION__);                        \
+        }                                                                 \
+    } while (0)
+
+#endif // DPL_ASSERT_H
diff --git a/commons/modules/core/include/dpl/availability.h b/commons/modules/core/include/dpl/availability.h
new file mode 100644 (file)
index 0000000..0813892
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        availability.h
+ * @author      Jihoon Chung (jihoon.chung@samsung.com)
+ * @version     1.0
+ */
+#ifndef DPL_AVAILABILITY_H
+#define DPL_AVAILABILITY_H
+
+#define DPL_DEPRECATED __attribute__((deprecated))
+#define DPL_DEPRECATED_WITH_MESSAGE(msg) __attribute__((deprecated(msg)))
+
+#define DPL_UNUSED __attribute__((unused))
+#define DPL_UNUSED_PARAM(variable) (void)variable
+
+#endif // DPL_AVAILABILITY_H
diff --git a/commons/modules/core/include/dpl/char_traits.h b/commons/modules/core/include/dpl/char_traits.h
new file mode 100644 (file)
index 0000000..eb2988f
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        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
+ */
+#ifndef DPL_CHAR_TRAITS
+#define DPL_CHAR_TRAITS
+
+#include <cstring>
+#include <string>
+#include <ostream>
+#include <algorithm>
+#include <dpl/exception.h>
+
+namespace DPL {
+typedef std::char_traits<wchar_t> CharTraits;
+} // namespace DPL
+
+#endif // DPL_CHAR_TRAITS
diff --git a/commons/modules/core/include/dpl/colors.h b/commons/modules/core/include/dpl/colors.h
new file mode 100644 (file)
index 0000000..c7cfd53
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        colors.h
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       Some constants with definition of colors for Console
+ *              and html output
+ */
+
+#ifndef DPL_COLORS_H
+#define DPL_COLORS_H
+
+namespace DPL {
+namespace Colors {
+namespace Text {
+extern const char* BOLD_GREEN_BEGIN;
+extern const char* BOLD_GREEN_END;
+extern const char* PURPLE_BEGIN;
+extern const char* PURPLE_END;
+extern const char* RED_BEGIN;
+extern const char* RED_END;
+extern const char* GREEN_BEGIN;
+extern const char* GREEN_END;
+extern const char* CYAN_BEGIN;
+extern const char* CYAN_END;
+extern const char* BOLD_RED_BEGIN;
+extern const char* BOLD_RED_END;
+extern const char* BOLD_YELLOW_BEGIN;
+extern const char* BOLD_YELLOW_END;
+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 {
+extern const char* BOLD_GREEN_BEGIN;
+extern const char* BOLD_GREEN_END;
+extern const char* PURPLE_BEGIN;
+extern const char* PURPLE_END;
+extern const char* RED_BEGIN;
+extern const char* RED_END;
+extern const char* GREEN_BEGIN;
+extern const char* GREEN_END;
+extern const char* CYAN_BEGIN;
+extern const char* CYAN_END;
+extern const char* BOLD_RED_BEGIN;
+extern const char* BOLD_RED_END;
+extern const char* BOLD_YELLOW_BEGIN;
+extern const char* BOLD_YELLOW_END;
+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/commons/modules/core/include/dpl/errno_string.h b/commons/modules/core/include/dpl/errno_string.h
new file mode 100644 (file)
index 0000000..446dbc9
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        errno_string.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of errno string
+ */
+#ifndef DPL_ERRNO_STRING_H
+#define DPL_ERRNO_STRING_H
+
+#include <dpl/exception.h>
+#include <string>
+#include <cerrno>
+
+namespace DPL {
+DECLARE_EXCEPTION_TYPE(DPL::Exception, InvalidErrnoValue)
+
+std::string GetErrnoString(int error = errno);
+} // namespace DPL
+
+#endif // DPL_ERRNO_STRING_H
diff --git a/commons/modules/core/include/dpl/exception.h b/commons/modules/core/include/dpl/exception.h
new file mode 100644 (file)
index 0000000..cdbdc53
--- /dev/null
@@ -0,0 +1,385 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    exception.h
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version 1.0
+ * @brief   Header file for base exception
+ */
+#ifndef DPL_EXCEPTION_H
+#define DPL_EXCEPTION_H
+
+#include <string>
+#include <cstring>
+#include <cstdio>
+#include <exception>
+#include <cstdlib>
+#include <sstream>
+
+namespace DPL {
+void LogUnhandledException(const std::string &str);
+void LogUnhandledException(const std::string &str,
+                           const char *filename,
+                           int line,
+                           const char *function);
+}
+
+namespace DPL {
+class Exception
+{
+  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);
+        }
+
+        ++m_exceptionCount;
+        m_lastException = exception;
+    }
+
+    static void UnRef(Exception* e)
+    {
+        if (m_lastException == e) {
+            m_lastException = NULL;
+        }
+
+        --m_exceptionCount;
+
+        if (!m_exceptionCount) {
+            std::set_terminate(m_terminateHandler);
+            m_terminateHandler = NULL;
+        }
+    }
+
+    static void TerminateHandler()
+    {
+        if (m_lastException != NULL) {
+            DisplayKnownException(*m_lastException);
+            abort();
+        } else {
+            DisplayUnknownException();
+            abort();
+        }
+    }
+
+    Exception *m_reason;
+    std::string m_path;
+    std::string m_function;
+    int m_line;
+
+  protected:
+    std::string m_message;
+    std::string m_className;
+
+  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;33mException trace:\033[m\n\n";
+        message << e.DumpToString();
+        message << "\033[1;31m\n=== Will now abort ===\033[m\n";
+
+        return message.str();
+    }
+
+    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";
+
+        return message.str();
+    }
+
+    static void DisplayKnownException(const Exception& e)
+    {
+        LogUnhandledException(KnownExceptionToString(e).c_str());
+    }
+
+    static void DisplayUnknownException()
+    {
+        LogUnhandledException(UnknownExceptionToString().c_str());
+    }
+
+    Exception(const Exception &other)
+    {
+        // Deep copy
+        if (other.m_reason != NULL) {
+            m_reason = new Exception(*other.m_reason);
+        } else {
+            m_reason = NULL;
+        }
+
+        m_message = other.m_message;
+        m_path = other.m_path;
+        m_function = other.m_function;
+        m_line = other.m_line;
+
+        m_className = other.m_className;
+
+        AddRef(this);
+    }
+
+    const Exception &operator =(const Exception &other)
+    {
+        if (this == &other) {
+            return *this;
+        }
+
+        // Deep copy
+        if (other.m_reason != NULL) {
+            m_reason = new Exception(*other.m_reason);
+        } else {
+            m_reason = NULL;
+        }
+
+        m_message = other.m_message;
+        m_path = other.m_path;
+        m_function = other.m_function;
+        m_line = other.m_line;
+
+        m_className = other.m_className;
+
+        AddRef(this);
+
+        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)
+    {
+        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)
+    {
+        AddRef(this);
+    }
+
+    virtual ~Exception() throw()
+    {
+        if (m_reason != NULL) {
+            delete m_reason;
+            m_reason = NULL;
+        }
+
+        UnRef(this);
+    }
+
+    void Dump() const
+    {
+        // Show reason first
+        if (m_reason != NULL) {
+            m_reason->Dump();
+        }
+
+        // Afterward, dump exception
+        const char *file = strchr(m_path.c_str(), '/');
+
+        if (file == NULL) {
+            file = m_path.c_str();
+        } else {
+            ++file;
+        }
+
+        printf("\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() ? "<EMPTY>" : m_message.c_str());
+    }
+
+    std::string DumpToString() const
+    {
+        std::string ret;
+        if (m_reason != NULL) {
+            ret = m_reason->DumpToString();
+        }
+
+        const char *file = strchr(m_path.c_str(), '/');
+
+        if (file == NULL) {
+            file = m_path.c_str();
+        } 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() ? "<EMPTY>" : m_message.c_str());
+
+        buf[sizeof(buf) - 1] = '\n';
+        ret += buf;
+
+        return ret;
+    }
+
+    Exception *GetReason() const
+    {
+        return m_reason;
+    }
+
+    std::string GetPath() const
+    {
+        return m_path;
+    }
+
+    std::string GetFunction() const
+    {
+        return m_function;
+    }
+
+    int GetLine() const
+    {
+        return m_line;
+    }
+
+    std::string GetMessage() const
+    {
+        return m_message;
+    }
+
+    std::string GetClassName() const
+    {
+        return m_className;
+    }
+};
+} // namespace DPL
+
+#define Try try
+
+#define Throw(ClassName) \
+    throw ClassName(__FILE__, __FUNCTION__, __LINE__)
+
+#define ThrowMsg(ClassName, Message)                                                 \
+    do                                                                               \
+    {                                                                                \
+        std::ostringstream dplLoggingStream;                                         \
+        dplLoggingStream << Message;                                                 \
+        throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str());   \
+    } while (0)
+
+#define ReThrow(ClassName) \
+    throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception)
+
+#define ReThrowMsg(ClassName, 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                                                                                                                \
+    {                                                                                                                                     \
+      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)                                                                            \
+        {                                                                                                                                 \
+            BaseClass::m_className = #Class;                                                                                              \
+        }                                                                                                                                 \
+    };
+
+#define UNHANDLED_EXCEPTION_HANDLER_BEGIN try
+
+#define UNHANDLED_EXCEPTION_HANDLER_END                                                                   \
+    catch (const DPL::Exception &exception)                                                               \
+    {                                                                                                     \
+        std::ostringstream msg;                                                                           \
+        msg << DPL::Exception::KnownExceptionToString(exception);                                         \
+        DPL::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
+        abort();                                                                                          \
+    }                                                                                                     \
+    catch (std::exception& e)                                                                             \
+    {                                                                                                     \
+        std::ostringstream msg;                                                                           \
+        msg << e.what();                                                                                  \
+        msg << "\n";                                                                                      \
+        msg << DPL::Exception::UnknownExceptionToString();                                                \
+        DPL::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
+        abort();                                                                                          \
+    }                                                                                                     \
+    catch (...)                                                                                           \
+    {                                                                                                     \
+        std::ostringstream msg;                                                                           \
+        msg << DPL::Exception::UnknownExceptionToString();                                                \
+        DPL::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
+        abort();                                                                                          \
+    }
+
+namespace DPL {
+namespace CommonException {
+/**
+ * Internal exception definitions
+ *
+ * These should normally not happen.
+ * Usually, exception trace with internal error includes
+ * important messages.
+ */
+DECLARE_EXCEPTION_TYPE(Exception, InternalError) ///< Unexpected error from
+                                                 // underlying libraries or
+                                                 // kernel
+}
+}
+
+#endif // DPL_EXCEPTION_H
diff --git a/commons/modules/core/include/dpl/foreach.h b/commons/modules/core/include/dpl/foreach.h
new file mode 100644 (file)
index 0000000..bbe477a
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        foreach.h
+ * @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
+ */
+#ifndef DPL_FOREACH_H
+#define DPL_FOREACH_H
+
+#include <dpl/preprocessor.h>
+
+namespace DPL {
+namespace Private {
+/*
+ * Used to detect type of valid reference to value object.
+ */
+template <typename T>
+T& ValueReference(T& t)
+{
+    return(t);
+}
+
+template <typename T>
+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 =                  \
+             temporaryName.begin();                                     \
+         (iterator) != temporaryName.end(); ++iterator)
+
+#define FOREACH(iterator, container)                                    \
+    DPL_FOREACH_IMPL(                                                   \
+        DPL_MACRO_CONCAT(foreachContainerReference, __COUNTER__),       \
+        iterator,                                      \
+        container)
+
+#endif // DPL_FOREACH_H
diff --git a/commons/modules/core/include/dpl/free_deleter.h b/commons/modules/core/include/dpl/free_deleter.h
new file mode 100644 (file)
index 0000000..4a09904
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        free_deleter.h
+ * @author      Pawel Czajkowski (p.czajkowski@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file deleter with use std::free()
+ */
+#ifndef FREE_DELETER_H
+#define FREE_DELETER_H
+
+#include <cstdlib>
+namespace DPL
+{
+struct free_deleter
+{
+    void operator()(void *p) { std::free(p); }
+};
+}// DPL
+#endif // FREE_DELETER_H
diff --git a/commons/modules/core/include/dpl/generic_event.h b/commons/modules/core/include/dpl/generic_event.h
new file mode 100644 (file)
index 0000000..b20d913
--- /dev/null
@@ -0,0 +1,639 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        generic_event.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of MVC generic event
+ */
+#ifndef DPL_GENERIC_EVENT_H
+#define DPL_GENERIC_EVENT_H
+
+namespace DPL {
+class EventSender
+{
+  public:
+    explicit EventSender(void *sender) :
+        m_sender(sender)
+    {}
+
+    void* GetSender() const
+    {
+        return m_sender;
+    }
+
+  private:
+    void *m_sender;
+};
+
+class GenericEvent
+{
+  protected:
+    void *m_sender;
+
+  public:
+    explicit GenericEvent(const EventSender &sender) :
+        m_sender(sender.GetSender())
+    {}
+
+    virtual ~GenericEvent()
+    {}
+
+    void *GetSender() const
+    {
+        return m_sender;
+    }
+};
+
+class GenericEvent0 :
+    public GenericEvent
+{
+  public:
+    explicit GenericEvent0(const EventSender &sender) :
+        GenericEvent(sender)
+    {}
+
+    virtual ~GenericEvent0()
+    {}
+};
+
+template<typename Arg0Type>
+class GenericEvent1 :
+    public GenericEvent0
+{
+  public:
+    typedef Arg0Type Arg0;
+
+  protected:
+    Arg0 m_arg0;
+
+  public:
+    explicit GenericEvent1(const EventSender &sender) :
+        GenericEvent0(sender)
+    {}
+
+    GenericEvent1(Arg0 arg0, const EventSender &sender) :
+        GenericEvent0(sender),
+        m_arg0(arg0)
+    {}
+
+    virtual ~GenericEvent1()
+    {}
+
+    Arg0 GetArg0() const
+    {
+        return m_arg0;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type>
+class GenericEvent2 :
+    public GenericEvent1<Arg0Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+
+  protected:
+    Arg1 m_arg1;
+
+  public:
+    explicit GenericEvent2(const EventSender &sender) :
+        GenericEvent1<Arg0Type>(sender)
+    {}
+
+    GenericEvent2(Arg0 arg0, Arg1 arg1, const EventSender &sender) :
+        GenericEvent1<Arg0Type>(arg0, sender),
+        m_arg1(arg1)
+    {}
+
+    virtual ~GenericEvent2()
+    {}
+
+    Arg1 GetArg1() const
+    {
+        return m_arg1;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type>
+class GenericEvent3 :
+    public GenericEvent2<Arg0Type, Arg1Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+
+  protected:
+    Arg2 m_arg2;
+
+  public:
+    explicit GenericEvent3(const EventSender &sender) :
+        GenericEvent2<Arg0Type, Arg1Type>(sender)
+    {}
+
+    GenericEvent3(Arg0 arg0, Arg1 arg1, Arg2 arg2, const EventSender &sender) :
+        GenericEvent2<Arg0Type, Arg1Type>(arg0, arg1, sender),
+        m_arg2(arg2)
+    {}
+
+    virtual ~GenericEvent3()
+    {}
+
+    Arg2 GetArg2() const
+    {
+        return m_arg2;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type,
+         typename Arg3Type>
+class GenericEvent4 :
+    public GenericEvent3<Arg0Type, Arg1Type, Arg2Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+    typedef Arg3Type Arg3;
+
+  protected:
+    Arg3 m_arg3;
+
+  public:
+    explicit GenericEvent4(const EventSender &sender) :
+        GenericEvent3<Arg0Type, Arg1Type, Arg2Type>(sender)
+    {}
+
+    GenericEvent4(Arg0 arg0,
+                  Arg1 arg1,
+                  Arg2 arg2,
+                  Arg3 arg3,
+                  const EventSender &sender) :
+        GenericEvent3<Arg0Type, Arg1Type, Arg2Type>(arg0, arg1, arg2, sender),
+        m_arg3(arg3)
+    {}
+
+    virtual ~GenericEvent4()
+    {}
+
+    Arg3 GetArg3() const
+    {
+        return m_arg3;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type,
+         typename Arg3Type, typename Arg4Type>
+class GenericEvent5 :
+    public GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+    typedef Arg3Type Arg3;
+    typedef Arg4Type Arg4;
+
+  protected:
+    Arg4 m_arg4;
+
+  public:
+    explicit GenericEvent5(const EventSender &sender) :
+        GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>(sender)
+    {}
+
+    GenericEvent5(Arg0 arg0,
+                  Arg1 arg1,
+                  Arg2 arg2,
+                  Arg3 arg3,
+                  Arg4 arg4,
+                  const EventSender &sender) :
+        GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>(arg0, arg1, arg2,
+                                                              arg3, sender),
+        m_arg4(arg4)
+    {}
+
+    virtual ~GenericEvent5()
+    {}
+
+    Arg4 GetArg4() const
+    {
+        return m_arg4;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type,
+         typename Arg3Type, typename Arg4Type, typename Arg5Type>
+class GenericEvent6 :
+    public GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+    typedef Arg3Type Arg3;
+    typedef Arg4Type Arg4;
+    typedef Arg5Type Arg5;
+
+  protected:
+    Arg5 m_arg5;
+
+  public:
+    explicit GenericEvent6(const EventSender &sender) :
+        GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type>(sender)
+    {}
+
+    GenericEvent6(Arg0 arg0,
+                  Arg1 arg1,
+                  Arg2 arg2,
+                  Arg3 arg3,
+                  Arg4 arg4,
+                  Arg5 arg5,
+                  const EventSender &sender) :
+        GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type>(arg0,
+                                                                        arg1,
+                                                                        arg2,
+                                                                        arg3,
+                                                                        arg4,
+                                                                        sender),
+        m_arg5(arg5)
+    {}
+
+    virtual ~GenericEvent6()
+    {}
+
+    Arg5 GetArg5() const
+    {
+        return m_arg5;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type,
+         typename Arg3Type, typename Arg4Type, typename Arg5Type,
+         typename Arg6Type>
+class GenericEvent7 :
+    public GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                         Arg5Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+    typedef Arg3Type Arg3;
+    typedef Arg4Type Arg4;
+    typedef Arg5Type Arg5;
+    typedef Arg6Type Arg6;
+
+  protected:
+    Arg6 m_arg6;
+
+  public:
+    explicit GenericEvent7(const EventSender &sender) :
+        GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                      Arg5Type>(sender)
+    {}
+
+    GenericEvent7(Arg0 arg0,
+                  Arg1 arg1,
+                  Arg2 arg2,
+                  Arg3 arg3,
+                  Arg4 arg4,
+                  Arg5 arg5,
+                  Arg6 arg6,
+                  const EventSender &sender) :
+        GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                      Arg5Type>(arg0, arg1, arg2, arg3, arg4, arg5, sender),
+        m_arg6(arg6)
+    {}
+
+    virtual ~GenericEvent7()
+    {}
+
+    Arg6 GetArg6() const
+    {
+        return m_arg6;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type,
+         typename Arg3Type, typename Arg4Type, typename Arg5Type,
+         typename Arg6Type,
+         typename Arg7Type>
+class GenericEvent8 :
+    public GenericEvent7<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                         Arg5Type, Arg6Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+    typedef Arg3Type Arg3;
+    typedef Arg4Type Arg4;
+    typedef Arg5Type Arg5;
+    typedef Arg6Type Arg6;
+    typedef Arg7Type Arg7;
+
+  protected:
+    Arg7 m_arg7;
+
+  public:
+    explicit GenericEvent8(const EventSender &sender) :
+        GenericEvent7<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                      Arg5Type, Arg6Type>(sender)
+    {}
+
+    GenericEvent8(Arg0 arg0,
+                  Arg1 arg1,
+                  Arg2 arg2,
+                  Arg3 arg3,
+                  Arg4 arg4,
+                  Arg5 arg5,
+                  Arg6 arg6,
+                  Arg7 arg7,
+                  const EventSender &sender) :
+        GenericEvent7<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                      Arg5Type, Arg6Type>(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                                         \
+    {                                                                       \
+      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<Arg0Type>                                 \
+    {                                                                         \
+      public:                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                       \
+            DPL::GenericEvent1<Arg0Type>(sender)                            \
+        {                                                                     \
+        }                                                                     \
+                                                                              \
+        explicit ClassName(Arg0Type arg0,                                     \
+                           const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                 \
+            DPL::GenericEvent1<Arg0Type>(arg0, sender)                      \
+        {                                                                     \
+        }                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_2(ClassName, Arg0Type, Arg1Type)                \
+    class ClassName :                                                                     \
+        public DPL::GenericEvent2<Arg0Type, Arg1Type>                       \
+    {                                                                         \
+      public:                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                       \
+            DPL::GenericEvent2<Arg0Type, Arg1Type>(sender)                  \
+        {                                                                     \
+        }                                                                     \
+                                                                              \
+        ClassName(Arg0Type arg0, Arg1Type arg1,                               \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                 \
+            DPL::GenericEvent2<Arg0Type, Arg1Type>(arg0, arg1, sender)      \
+        {                                                                     \
+        }                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_3(ClassName, Arg0Type, Arg1Type, Arg2Type)                      \
+    class ClassName :                                                                                     \
+        public DPL::GenericEvent3<Arg0Type, Arg1Type, Arg2Type>                             \
+    {                                                                                         \
+      public:                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                 \
+            DPL::GenericEvent3<Arg0Type, Arg1Type, Arg2Type>(sender)                        \
+        {                                                                                     \
+        }                                                                                     \
+                                                                                              \
+        ClassName(Arg0Type arg0, Arg1Type arg1, Arg2Type arg2,                                \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                                 \
+            DPL::GenericEvent3<Arg0Type, Arg1Type, Arg2Type>(arg0, \
+                                                             arg1, \
+                                                             arg2, \
+                                                             sender)      \
+        {                                                                                     \
+        }                                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_4(ClassName, \
+                                Arg0Type, \
+                                Arg1Type, \
+                                Arg2Type, \
+                                Arg3Type)                            \
+    class ClassName :                                                                                                     \
+        public DPL::GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>                                   \
+    {                                                                                                         \
+      public:                                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                                 \
+            DPL::GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>(sender)                              \
+        {                                                                                                     \
+        }                                                                                                     \
+                                                                                                              \
+        ClassName(Arg0Type arg0, Arg1Type arg1, Arg2Type arg2, Arg3Type arg3,                                 \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                                                 \
+            DPL::GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>(arg0, \
+                                                                       arg1, \
+                                                                       arg2, \
+                                                                       arg3, \
+                                                                       sender)      \
+        {                                                                                                     \
+        }                                                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_5(ClassName, \
+                                Arg0Type, \
+                                Arg1Type, \
+                                Arg2Type, \
+                                Arg3Type, \
+                                Arg4Type)                                  \
+    class ClassName :                                                                                                                     \
+        public DPL::GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, \
+                                  Arg4Type>                                         \
+    {                                                                                                                         \
+      public:                                                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                                                 \
+            DPL::GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type>( \
+                sender)                                    \
+        {                                                                                                                     \
+        }                                                                                                                     \
+                                                                                                                              \
+        ClassName(Arg0Type arg0, \
+                  Arg1Type arg1, \
+                  Arg2Type arg2, \
+                  Arg3Type arg3, \
+                  Arg4Type arg4,                                  \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                                                                 \
+            DPL::GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type>( \
+                arg0, \
+                arg1, \
+                arg2, \
+                arg3, \
+                arg4, \
+                sender)      \
+        {                                                                                                                     \
+        }                                                                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_6(ClassName, \
+                                Arg0Type, \
+                                Arg1Type, \
+                                Arg2Type, \
+                                Arg3Type, \
+                                Arg4Type, \
+                                Arg5Type)                                        \
+    class ClassName :                                                                                                                                     \
+        public DPL::GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, \
+                                  Arg4Type, Arg5Type>                                               \
+    {                                                                                                                                         \
+      public:                                                                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                                                                 \
+            DPL::GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type>(sender)                                          \
+        {                                                                                                                                     \
+        }                                                                                                                                     \
+                                                                                                                                              \
+        ClassName(Arg0Type arg0, \
+                  Arg1Type arg1, \
+                  Arg2Type arg2, \
+                  Arg3Type arg3, \
+                  Arg4Type arg4, \
+                  Arg5Type arg5,                                   \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                                                                                 \
+            DPL::GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type>(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<Arg0Type, Arg1Type, Arg2Type, Arg3Type, \
+                                  Arg4Type, Arg5Type, Arg6Type>                                                     \
+    {                                                                                                                                                         \
+      public:                                                                                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                                                                                 \
+            DPL::GenericEvent7<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type, Arg6Type>(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<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type, Arg6Type>(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<Arg0Type, Arg1Type, Arg2Type, Arg3Type, \
+                                  Arg4Type, Arg5Type, Arg6Type, Arg7Type>                                                           \
+    {                                                                                                                                                                         \
+      public:                                                                                                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                                                                                                 \
+            DPL::GenericEvent8<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type, Arg6Type, Arg7Type>(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<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type, Arg6Type, Arg7Type>(arg0, \
+                                                             arg1, \
+                                                             arg2, \
+                                                             arg3, \
+                                                             arg4, \
+                                                             arg5, \
+                                                             arg6, \
+                                                             arg7, \
+                                                             sender)      \
+        {                                                                                                                                                                     \
+        }                                                                                                                                                                     \
+    };
+
+#endif // DPL_GENERIC_EVENT_H
diff --git a/commons/modules/core/include/dpl/mutex.h b/commons/modules/core/include/dpl/mutex.h
new file mode 100644 (file)
index 0000000..d55871f
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        mutex.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of mutex
+ */
+#ifndef DPL_MUTEX_H
+#define DPL_MUTEX_H
+
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <dpl/availability.h>
+#include <pthread.h>
+
+namespace DPL {
+class Mutex :
+    private Noncopyable
+{
+  public:
+    class ScopedLock :
+        private Noncopyable
+    {
+      private:
+        Mutex *m_mutex;
+
+      public:
+        explicit ScopedLock(Mutex *mutex);
+        ~ScopedLock();
+    };
+
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, CreateFailed)
+        DECLARE_EXCEPTION_TYPE(Base, LockFailed)
+        DECLARE_EXCEPTION_TYPE(Base, UnlockFailed)
+    };
+
+  private:
+    mutable pthread_mutex_t m_mutex;
+
+    void Lock() const;
+    void Unlock() const;
+
+  public:
+    Mutex();
+    ~Mutex();
+} DPL_DEPRECATED_WITH_MESSAGE("Use std::mutex instead");
+} // namespace DPL
+
+#endif // DPL_MUTEX_H
diff --git a/commons/modules/core/include/dpl/noncopyable.h b/commons/modules/core/include/dpl/noncopyable.h
new file mode 100644 (file)
index 0000000..98d57dd
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        noncopyable
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of noncopyable
+ */
+#ifndef DPL_NONCOPYABLE_H
+#define DPL_NONCOPYABLE_H
+
+namespace DPL {
+class Noncopyable
+{
+  private:
+    Noncopyable(const Noncopyable &);
+    const Noncopyable &operator=(const Noncopyable &);
+
+  public:
+    Noncopyable();
+    virtual ~Noncopyable();
+};
+} // namespace DPL
+
+#endif // DPL_NONCOPYABLE_H
diff --git a/commons/modules/core/include/dpl/optional_typedefs.h b/commons/modules/core/include/dpl/optional_typedefs.h
new file mode 100644 (file)
index 0000000..dd68dc2
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#ifndef DPL_OPTIONAL_TYPEDEFS_H
+#define DPL_OPTIONAL_TYPEDEFS_H
+
+#include <string>
+#include <dpl/string.h>
+#include <boost/optional.hpp>
+
+namespace DPL {
+typedef boost::optional<String> OptionalString;
+typedef boost::optional<int> OptionalInt;
+typedef boost::optional<unsigned int> OptionalUInt;
+typedef boost::optional<bool> OptionalBool;
+typedef boost::optional<float> OptionalFloat;
+typedef boost::optional<std::string> OptionalStdString;
+} //namespace DPL
+
+#endif /* DPL_OPTIONAL_TYPEDEFS_H */
+
diff --git a/commons/modules/core/include/dpl/preprocessor.h b/commons/modules/core/include/dpl/preprocessor.h
new file mode 100644 (file)
index 0000000..6fca34c
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        preprocessor.h
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains some usefull macros.
+ */
+
+#ifndef DPL_PREPROCESSOR_H
+#define DPL_PREPROCESSOR_H
+
+#define DPL_MACRO_CONCAT_IMPL(x, y) x##y
+#define DPL_MACRO_CONCAT(x, y) DPL_MACRO_CONCAT_IMPL(x, y)
+
+#ifdef __COUNTER__
+#define DPL_ANONYMOUS_VARIABLE(name) DPL_MACRO_CONCAT(name, __COUNTER__)
+#else
+#define DPL_ANONYMOUS_VARIABLE(name) DPL_MACRO_CONCAT(name, __LINE__)
+#endif
+
+#endif //DPL_PREPROCESSOR_H
diff --git a/commons/modules/core/include/dpl/recursive_mutex.h b/commons/modules/core/include/dpl/recursive_mutex.h
new file mode 100644 (file)
index 0000000..a950ee5
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        recursive_mutex.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of recursive mutex
+ */
+#ifndef DPL_RECURSIVE_MUTEX_H
+#define DPL_RECURSIVE_MUTEX_H
+
+#include <dpl/availability.h>
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <pthread.h>
+
+namespace DPL {
+class RecursiveMutex :
+    private Noncopyable
+{
+  public:
+    class ScopedLock :
+        private Noncopyable
+    {
+      private:
+        RecursiveMutex *m_mutex;
+
+      public:
+        ScopedLock(RecursiveMutex *mutex);
+        virtual ~ScopedLock();
+    };
+
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, CreateFailed)
+        DECLARE_EXCEPTION_TYPE(Base, DestroyFailed)
+        DECLARE_EXCEPTION_TYPE(Base, LockFailed)
+        DECLARE_EXCEPTION_TYPE(Base, UnlockFailed)
+    };
+
+  private:
+    mutable pthread_mutex_t m_mutex;
+
+    void Lock() const;
+    void Unlock() const;
+
+  public:
+    explicit RecursiveMutex();
+    virtual ~RecursiveMutex();
+} DPL_DEPRECATED_WITH_MESSAGE("Use std::recursive_mutex instead");
+} // namespace DPL
+
+#endif // DPL_RECURSIVE_MUTEX_H
diff --git a/commons/modules/core/include/dpl/scoped_free.h b/commons/modules/core/include/dpl/scoped_free.h
new file mode 100644 (file)
index 0000000..7bebe39
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*!
+ * @file        scoped_free.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of scoped free RAII
+ */
+
+#ifndef DPL_SCOPED_FREE_H
+#define DPL_SCOPED_FREE_H
+
+#include <malloc.h>
+#include <cstddef>
+
+#include <dpl/scoped_resource.h>
+
+namespace DPL {
+template<typename Class>
+struct ScopedFreePolicy
+{
+    typedef Class* Type;
+    static Type NullValue()
+    {
+        return NULL;
+    }
+    static void Destroy(Type ptr)
+    {
+        free(ptr);
+    }
+};
+
+template<typename Memory>
+class ScopedFree : public ScopedResource<ScopedFreePolicy<Memory> >
+{
+    typedef ScopedFreePolicy<Memory> Policy;
+    typedef ScopedResource<Policy> BaseType;
+
+  public:
+    explicit ScopedFree(Memory *ptr = Policy::NullValue()) : BaseType(ptr) { }
+};
+} // namespace DPL
+
+#endif // DPL_SCOPED_FREE_H
diff --git a/commons/modules/core/include/dpl/scoped_resource.h b/commons/modules/core/include/dpl/scoped_resource.h
new file mode 100644 (file)
index 0000000..63287da
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        scoped_resource.h
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of scoped resource pattern
+ */
+#ifndef DPL_SCOPED_RESOURCE_H
+#define DPL_SCOPED_RESOURCE_H
+
+#include <dpl/noncopyable.h>
+
+namespace DPL {
+template<typename ClassPolicy>
+class ScopedResource :
+    private Noncopyable
+{
+  public:
+    typedef typename ClassPolicy::Type ValueType;
+    typedef ScopedResource<ClassPolicy> ThisType;
+
+  protected:
+    ValueType m_value;
+
+  public:
+    explicit ScopedResource(ValueType value) : m_value(value) { }
+
+    ~ScopedResource()
+    {
+        ClassPolicy::Destroy(m_value);
+    }
+
+    ValueType Get() const
+    {
+        return m_value;
+    }
+
+    void Reset(ValueType value = ClassPolicy::NullValue())
+    {
+        ClassPolicy::Destroy(m_value);
+        m_value = value;
+    }
+
+    ValueType Release()
+    {
+        ValueType value = m_value;
+        m_value = ClassPolicy::NullValue();
+        return value;
+    }
+    typedef ValueType ThisType::*UnknownBoolType;
+
+    operator UnknownBoolType() const
+    {
+        return m_value == ClassPolicy::NullValue() ?
+               0 : //0 is valid here because it converts to false
+               &ThisType::m_value; //it converts to true
+    }
+
+    bool operator !() const
+    {
+        return m_value == ClassPolicy::NullValue();
+    }
+};
+} // namespace DPL
+
+#endif // DPL_SCOPED_RESOURCE_H
diff --git a/commons/modules/core/include/dpl/serialization.h b/commons/modules/core/include/dpl/serialization.h
new file mode 100644 (file)
index 0000000..d72c488
--- /dev/null
@@ -0,0 +1,327 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file    serialization.h
+ * @author  Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version 1.0
+ * @brief   Interfaces and templates used for data serialization.
+ */
+#ifndef SERIALIZATION_H
+#define SERIALIZATION_H
+
+#include <string>
+#include <vector>
+#include <list>
+#include <map>
+
+namespace DPL {
+// Abstract data stream buffer
+class IStream
+{
+  public:
+    virtual void Read(size_t num, void * bytes) = 0;
+    virtual void Write(size_t num, const void * bytes) = 0;
+    virtual ~IStream(){}
+};
+
+// Serializable interface
+class ISerializable
+{
+  public:
+    /*    ISerializable(){};
+     *    ISerializable(IStream&){}; */
+    virtual void Serialize(IStream &) const = 0;
+    virtual ~ISerializable(){}
+};
+
+struct Serialization {
+    // 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);
+    }
+
+    // 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);
+    }
+
+    // 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());
+    }
+
+    // STL templates
+
+    // std::list
+    template <typename T>
+    static void Serialize(IStream& stream, const std::list<T>& list)
+    {
+        int length = list.size();
+        stream.Write(sizeof(length), &length);
+        for (typename std::list<T>::const_iterator list_iter = list.begin();
+             list_iter != list.end(); list_iter++)
+        {
+            Serialize(stream, *list_iter);
+        }
+    }
+    template <typename T>
+    static void Serialize(IStream& stream, const std::list<T>* const list)
+    {
+        Serialize(stream, *list);
+    }
+
+    // std::vector
+    template <typename T>
+    static void Serialize(IStream& stream, const std::vector<T>& vec)
+    {
+        int length = vec.size();
+        stream.Write(sizeof(length), &length);
+        for (typename std::vector<T>::const_iterator vec_iter = vec.begin();
+             vec_iter != vec.end(); vec_iter++)
+        {
+            Serialize(stream, *vec_iter);
+        }
+    }
+    template <typename T>
+    static void Serialize(IStream& stream, const std::vector<T>* const vec)
+    {
+        Serialize(stream, *vec);
+    }
+
+    // std::pair
+    template <typename A, typename B>
+    static void Serialize(IStream& stream, const std::pair<A, B>& p)
+    {
+        Serialize(stream, p.first);
+        Serialize(stream, p.second);
+    }
+    template <typename A, typename B>
+    static void Serialize(IStream& stream, const std::pair<A, B>* const p)
+    {
+        Serialize(stream, *p);
+    }
+
+    // std::map
+    template <typename K, typename T>
+    static void Serialize(IStream& stream, const std::map<K, T>& map)
+    {
+        int length = map.size();
+        stream.Write(sizeof(length), &length);
+        typename std::map<K, T>::const_iterator it;
+        for (it = map.begin(); it != map.end(); ++it) {
+            Serialize(stream, (*it).first);
+            Serialize(stream, (*it).second);
+        }
+    }
+    template <typename K, typename T>
+    static void Serialize(IStream& stream, const std::map<K, T>* const map)
+    {
+        Serialize(stream, *map);
+    }
+}; // struct Serialization
+
+struct Deserialization {
+    // deserialization
+    // normal functions
+
+    // ISerializable objects
+    // T instead of ISerializable is needed to call proper constructor
+    template <typename T>
+    static void Deserialize(IStream& stream, T& object)
+    {
+        object = T(stream);
+    }
+    template <typename T>
+    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);
+    }
+
+    // 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);
+    }
+
+    // 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
+
+    // std::list
+    template <typename T>
+    static void Deserialize(IStream& stream, std::list<T>& 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 <typename T>
+    static void Deserialize(IStream& stream, std::list<T>*& list)
+    {
+        list = new std::list<T>;
+        Deserialize(stream, *list);
+    }
+
+    // std::vector
+    template <typename T>
+    static void Deserialize(IStream& stream, std::vector<T>& 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 <typename T>
+    static void Deserialize(IStream& stream, std::vector<T>*& vec)
+    {
+        vec = new std::vector<T>;
+        Deserialize(stream, *vec);
+    }
+
+    // std::pair
+    template <typename A, typename B>
+    static void Deserialize(IStream& stream, std::pair<A, B>& p)
+    {
+        Deserialize(stream, p.first);
+        Deserialize(stream, p.second);
+    }
+    template <typename A, typename B>
+    static void Deserialize(IStream& stream, std::pair<A, B>*& p)
+    {
+        p = new std::pair<A, B>;
+        Deserialize(stream, *p);
+    }
+
+    // std::map
+    template <typename K, typename T>
+    static void Deserialize(IStream& stream, std::map<K, T>& 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 <typename K, typename T>
+    static void Deserialize(IStream& stream, std::map<K, T>*& map)
+    {
+        map = new std::map<K, T>;
+        Deserialize(stream, *map);
+    }
+}; // struct Deserialization
+} // namespace DPL
+
+#endif // SERIALIZATION_H
diff --git a/commons/modules/core/include/dpl/single_instance.h b/commons/modules/core/include/dpl/single_instance.h
new file mode 100644 (file)
index 0000000..afcaf52
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        single_instance.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of single instance
+ */
+#ifndef DPL_SINGLE_INSTANCE_H
+#define DPL_SINGLE_INSTANCE_H
+
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <string>
+
+namespace DPL {
+class SingleInstance :
+    private Noncopyable
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, LockError)
+        DECLARE_EXCEPTION_TYPE(Base, ReleaseError)
+    };
+
+  private:
+    bool m_locked;
+    int m_fdLock;
+
+  public:
+    SingleInstance();
+    virtual ~SingleInstance();
+
+    bool TryLock(const std::string &lockName);
+    void Release();
+};
+} // namespace DPL
+
+#endif // DPL_SINGLE_INSTANCE_H
diff --git a/commons/modules/core/include/dpl/singleton.h b/commons/modules/core/include/dpl/singleton.h
new file mode 100644 (file)
index 0000000..5cd2d32
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        singleton.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#ifndef DPL_SINGLETON_H
+#define DPL_SINGLETON_H
+
+#include <boost/optional.hpp>
+#include <dpl/thread.h>
+#include <dpl/assert.h>
+
+namespace DPL {
+template<typename Class>
+class Singleton :
+    private Class
+{
+    //
+    // Note:
+    //
+    // To remove posibility of instantiating directly Class,
+    // make Class' default constructor protected
+    //
+
+  private:
+    Singleton()
+    {}
+
+    typedef boost::optional<Thread *> OptionalThreadPtr;
+
+    static Singleton &InternalInstance();
+
+  public:
+    virtual ~Singleton()
+    {}
+
+    static Class &Instance();
+};
+} // namespace DPL
+
+#endif // DPL_SINGLETON_H
diff --git a/commons/modules/core/include/dpl/singleton_impl.h b/commons/modules/core/include/dpl/singleton_impl.h
new file mode 100644 (file)
index 0000000..12dbf32
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        singleton_impl.h
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#ifndef DPL_SINGLETON_IMPL_H
+#define DPL_SINGLETON_IMPL_H
+
+/*
+ * WARNING!
+ *
+ * If some singleton's implementation uses another singletons implementation,
+ * those templates make the second singleton a dubleton. Be warned. Try to use
+ * singleton_safe_impl.h if possible.
+ */
+
+namespace DPL {
+template<typename Class>
+Singleton<Class>& Singleton<Class>::InternalInstance()
+{
+    static Singleton<Class> instance;
+    return instance;
+}
+
+template<typename Class>
+Class &Singleton<Class>::Instance()
+{
+    Singleton<Class>& instance = Singleton<Class>::InternalInstance();
+    return instance;
+}
+} // namespace DPL
+
+#define IMPLEMENT_SINGLETON(Type)                                           \
+    template DPL::Singleton<Type>&DPL::Singleton<Type>::InternalInstance();    \
+    template Type & DPL::Singleton<Type>::Instance();                            \
+
+#endif // DPL_SINGLETON_IMPL_H
diff --git a/commons/modules/core/include/dpl/singleton_safe_impl.h b/commons/modules/core/include/dpl/singleton_safe_impl.h
new file mode 100644 (file)
index 0000000..c8923b7
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        singleton_safe_impl.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#ifndef DPL_SINGLETON_SAFE_IMPL_H
+#define DPL_SINGLETON_SAFE_IMPL_H
+
+#define IMPLEMENT_SAFE_SINGLETON(Class)                                        \
+    namespace DPL {                                                                \
+    template<>                                                                     \
+    Singleton<Class>&Singleton<Class>::InternalInstance()                         \
+    {                                                                              \
+        static Singleton<Class> instance;                                          \
+        return instance;                                                           \
+    }                                                                              \
+                                                                               \
+    template<>                                                                     \
+    Class & Singleton<Class>::Instance()                                            \
+    {                                                                              \
+        Singleton<Class>& instance = Singleton<Class>::InternalInstance();         \
+        return instance;                                                           \
+    }                                                                              \
+                                                                               \
+    template Singleton<Class>&Singleton<Class>::InternalInstance();               \
+    template Class & Singleton<Class>::Instance();                                  \
+    } // namespace DPL
+
+#endif // DPL_SINGLETON_SAFE_IMPL_H
diff --git a/commons/modules/core/include/dpl/string.h b/commons/modules/core/include/dpl/string.h
new file mode 100644 (file)
index 0000000..e4dc923
--- /dev/null
@@ -0,0 +1,157 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        string.h
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @version     1.0
+ */
+#ifndef DPL_STRING
+#define DPL_STRING
+
+#include <dpl/exception.h>
+#include <dpl/char_traits.h>
+#include <string>
+#include <ostream>
+#include <numeric>
+
+namespace DPL {
+// @brief DPL string
+typedef std::basic_string<wchar_t, CharTraits> String;
+
+// @brief String exception class
+class StringException
+{
+  public:
+    DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+
+    // @brief Invalid init for UTF8 to UTF32 converter
+    DECLARE_EXCEPTION_TYPE(Base, IconvInitErrorUTF8ToUTF32)
+
+    // @brief Invalid taStdContainerinit for UTF32 to UTF32 converter
+    DECLARE_EXCEPTION_TYPE(Base, IconvInitErrorUTF32ToUTF8)
+
+    // @brief Invalid conversion for UTF8 to UTF32 converter
+    DECLARE_EXCEPTION_TYPE(Base, IconvConvertErrorUTF8ToUTF32)
+
+    // @brief Invalid conversion for UTF8 to UTF32 converter
+    DECLARE_EXCEPTION_TYPE(Base, IconvConvertErrorUTF32ToUTF8)
+
+    // @brief Invalid ASCII character detected in FromASCII
+    DECLARE_EXCEPTION_TYPE(Base, InvalidASCIICharacter)
+
+    // @brief Invalid ASCII character detected in FromASCII
+    DECLARE_EXCEPTION_TYPE(Base, ICUInvalidCharacterFound)
+};
+
+//!\brief convert ASCII string to DPL::String
+String FromASCIIString(const std::string& aString);
+
+//!\brief convert UTF32 string to DPL::String
+String FromUTF32String(const std::wstring& aString);
+
+//@brief Returns String object created from UTF8 string
+//@param[in] aString input UTF-8 string
+String FromUTF8String(const std::string& aString);
+
+//@brief Returns String content as std::string
+std::string ToUTF8String(const String& aString);
+
+//@brief Compare two unicode strings
+int StringCompare(const String &left,
+                  const String &right,
+                  bool caseInsensitive = false);
+
+//@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] it InserterIterator that is used to save the generated substrings.
+template<typename StringType, typename Delimiters, typename InserterIterator>
+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) {
+        pos = str.find_first_of(delimiters, nextSearchStart);
+        length =
+            ((pos == StringType::npos) ? str.length() : pos) - nextSearchStart;
+
+        if (!ignoreEmpty || length > 0) {
+            *it = str.substr(nextSearchStart, length);
+            it++;
+        }
+
+        if (pos == StringType::npos) {
+            return;
+        }
+
+        nextSearchStart = pos + 1;
+    }
+}
+
+namespace Utils {
+
+template<typename T> class ConcatFunc : public std::binary_function<T, T, T>
+{
+public:
+    explicit ConcatFunc(const T & val) : m_delim(val) {}
+    T operator()(const T & arg1, const T & arg2) const
+    {
+        return arg1 + m_delim + arg2;
+    }
+private:
+    T m_delim;
+};
+
+}
+
+template<typename ForwardIterator>
+typename ForwardIterator::value_type Join(ForwardIterator begin, ForwardIterator end, typename ForwardIterator::value_type delim)
+{
+    typedef typename ForwardIterator::value_type value;
+    if(begin == end) return value();
+    Utils::ConcatFunc<value> func(delim);
+    ForwardIterator init = begin;
+    return std::accumulate(++begin, end, *init, func);
+}
+
+template<class StringType> void TrimLeft(StringType & obj, typename StringType::const_pointer separators)
+{
+    obj.erase(0, obj.find_first_not_of(separators));
+}
+
+template<class StringType> void TrimRight(StringType & obj, typename StringType::const_pointer separators)
+{
+    obj.erase(obj.find_last_not_of(separators)+1);
+}
+
+template<class StringType> void Trim(StringType & obj, typename StringType::const_pointer separators)
+{
+    TrimLeft(obj, separators);
+    TrimRight(obj, separators);
+}
+
+
+} //namespace DPL
+
+std::ostream& operator<<(std::ostream& aStream, const DPL::String& aString);
+
+#endif // DPL_STRING
diff --git a/commons/modules/core/include/dpl/thread.h b/commons/modules/core/include/dpl/thread.h
new file mode 100644 (file)
index 0000000..d61b79d
--- /dev/null
@@ -0,0 +1,396 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        thread.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of thread
+ */
+#ifndef DPL_THREAD_H
+#define DPL_THREAD_H
+
+#include <dpl/waitable_handle_watch_support.h>
+//#include <dpl/waitable_event.h>
+//#include <dpl/waitable_handle.h>
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <dpl/assert.h>
+#include <boost/optional.hpp>
+#include <stdint.h>
+#include <cstdlib>
+#include <pthread.h>
+#include <thread>
+#include <vector>
+#include <list>
+#include <mutex>
+
+namespace DPL {
+class Thread :
+    private Noncopyable,
+    public WaitableHandleWatchSupport
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, CreateFailed)
+        DECLARE_EXCEPTION_TYPE(Base, DestroyFailed)
+        DECLARE_EXCEPTION_TYPE(Base, RunFailed)
+        DECLARE_EXCEPTION_TYPE(Base, QuitFailed)
+        DECLARE_EXCEPTION_TYPE(Base, UnmanagedThread)
+    };
+
+    typedef void (*EventDeleteProc)(void *event, void *userParam);
+    typedef void (*EventDispatchProc)(void *event, void *userParam);
+
+  protected:
+    /**
+     * Main thread entry
+     * The method is intended to be overloaded with custom code.
+     * Default implementation just executes Exec method to process
+     * all thread exents
+     */
+    virtual int ThreadEntry();
+
+    /**
+     * Start processing of thread events
+     */
+    int Exec();
+
+  private:
+    struct InternalEvent
+    {
+        void *event;
+        void *userParam;
+        EventDispatchProc eventDispatchProc;
+        EventDeleteProc eventDeleteProc;
+
+        InternalEvent(void *eventArg,
+                      void *userParamArg,
+                      EventDispatchProc eventDispatchProcArg,
+                      EventDeleteProc eventDeleteProcArg) :
+            event(eventArg),
+            userParam(userParamArg),
+            eventDispatchProc(eventDispatchProcArg),
+            eventDeleteProc(eventDeleteProcArg)
+        {}
+    };
+
+    struct InternalTimedEvent :
+        InternalEvent
+    {
+        unsigned long dueTimeMiliseconds;
+        unsigned long registerTimeMiliseconds;
+
+        InternalTimedEvent(void *eventArg,
+                           void *userParamArg,
+                           unsigned long dueTimeMilisecondsArg,
+                           unsigned long registerTimeMilisecondsArg,
+                           EventDispatchProc eventDispatchProcArg,
+                           EventDeleteProc eventDeleteProcArg) :
+            InternalEvent(eventArg,
+                          userParamArg,
+                          eventDispatchProcArg,
+                          eventDeleteProcArg),
+            dueTimeMiliseconds(dueTimeMilisecondsArg),
+            registerTimeMiliseconds(registerTimeMilisecondsArg)
+        {}
+
+        bool operator<(const InternalTimedEvent &other)
+        {
+            return registerTimeMiliseconds + dueTimeMiliseconds >
+                   other.registerTimeMiliseconds + other.dueTimeMiliseconds;
+        }
+    };
+
+    // Internal event list
+    typedef std::list<InternalEvent> InternalEventList;
+
+    // Internal timed event list
+    typedef std::vector<InternalTimedEvent> InternalTimedEventVector;
+
+    // State managment
+    std::thread m_thread;
+    volatile bool m_abandon;
+    volatile bool m_running;
+    std::mutex m_stateMutex;
+    WaitableEvent m_quitEvent;
+
+    // Event processing
+    std::mutex m_eventMutex;
+    InternalEventList m_eventList;
+    WaitableEvent m_eventInvoker;
+
+    // Timed events processing
+    std::mutex m_timedEventMutex;
+    InternalTimedEventVector m_timedEventVector;
+    WaitableEvent m_timedEventInvoker;
+
+    // WaitableHandleWatchSupport
+    virtual Thread *GetInvokerThread();
+    virtual void HandleDirectInvoker();
+    bool m_directInvoke;
+
+    // Internals
+    unsigned long GetCurrentTimeMiliseconds() const;
+    void ProcessEvents();
+    void ProcessTimedEvents();
+
+    static void *StaticThreadEntry(void *param);
+
+  public:
+    explicit Thread();
+    virtual ~Thread();
+
+    /**
+     * Run thread. Does nothing if thread is already running
+     */
+    void Run();
+
+    /**
+     * Send quit message to thread and wait for its end
+     * Does nothing is thread is not running
+     */
+    void Quit();
+
+    /**
+     * Checks if current thread is main one
+     * Returns true if it is main program thread, false otherwise
+     */
+    static bool IsMainThread();
+
+    /**
+     * Current thread retrieval
+     * Returns DPL thread handle or NULL if it is main program thread
+     */
+    static Thread *GetCurrentThread();
+
+    /**
+     * Low-level event push, usually used only by EventSupport
+     */
+    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);
+
+    /**
+     * Sleep for a number of seconds
+     */
+    static void Sleep(uint64_t seconds);
+
+    /**
+     * Sleep for a number of miliseconds
+     */
+    static void MiliSleep(uint64_t miliseconds);
+
+    /**
+     * Sleep for a number of microseconds
+     */
+    static void MicroSleep(uint64_t microseconds);
+
+    /**
+     * Sleep for a number of nanoseconds
+     */
+    static void NanoSleep(uint64_t nanoseconds);
+};
+
+extern bool g_TLSforMainCreated;
+
+// In case of using TLV in main thread, pthread_exit(NULL) has to be called in
+// this thread explicitly.
+// On the other hand, possibly, because of the kernel bug, there exist
+// a problem, if any other thread than main exist during pthread_exit call
+// (process can become non-responsive)
+// TODO further investigation is required.
+template<typename Type>
+class ThreadLocalVariable :
+    public Noncopyable
+{
+  public:
+    typedef Type ValueType;
+
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, NullReference)
+        DECLARE_EXCEPTION_TYPE(Base, KeyCreateFailed)
+    };
+
+  private:
+    pthread_key_t m_key;
+
+    struct ManagedValue
+    {
+        ValueType value;
+        boost::optional<pthread_key_t> guardKey;
+    };
+
+    static void MainThreadExitClean()
+    {
+        // There is a possible bug in kernel. If this function is called
+        // before ALL threads are closed, process will hang!
+        // Because of that, by default this function has to be called in well
+        // known "threads state".
+
+        // pthread_exit(NULL);
+    }
+
+    static void InternalDestroy(void *specific)
+    {
+        // Destroy underlying type
+        ManagedValue *instance = static_cast<ManagedValue *>(specific);
+        if (!instance->guardKey) {
+            delete instance;
+        } else {
+            int result = pthread_setspecific(*(instance->guardKey), instance);
+
+            Assert(result == 0 &&
+                   "Failed to set thread local variable");
+        }
+    }
+
+    Type &Reference(bool allowInstantiate = false)
+    {
+        ManagedValue *instance =
+            static_cast<ManagedValue *>(pthread_getspecific(m_key));
+
+        if (!instance) {
+            // Check if it is allowed to instantiate
+            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()) {
+                    g_TLSforMainCreated = true;
+                    atexit(&MainThreadExitClean);
+                }
+            }
+
+            // Need to instantiate underlying type
+            instance = new ManagedValue();
+
+            int result = pthread_setspecific(m_key, instance);
+
+            Assert(result == 0 &&
+                   "Failed to set thread local variable");
+        }
+
+        return instance->value;
+    }
+
+  public:
+    ThreadLocalVariable()
+    {
+        int result = pthread_key_create(&m_key, &InternalDestroy);
+        if (result != 0) {
+            ThrowMsg(typename Exception::KeyCreateFailed,
+                     "Failed to allocate thread local variable: " << result);
+        }
+    }
+
+    ~ThreadLocalVariable()
+    {
+        pthread_key_delete(m_key);
+    }
+
+    Type &operator=(const Type &other)
+    {
+        Type &reference = Reference(true);
+        reference = other;
+        return reference;
+    }
+
+    bool IsNull() const
+    {
+        return pthread_getspecific(m_key) == NULL;
+    }
+
+    Type& operator*()
+    {
+        return Reference();
+    }
+
+    const Type& operator*() const
+    {
+        return Reference();
+    }
+
+    const Type* operator->() const
+    {
+        return &Reference();
+    }
+
+    Type* operator->()
+    {
+        return &Reference();
+    }
+
+    bool operator!() const
+    {
+        return IsNull();
+    }
+
+    void Reset()
+    {
+        ManagedValue *specific =
+            static_cast<ManagedValue *>(pthread_getspecific(m_key));
+
+        if (!specific) {
+            return;
+        }
+
+        // TODO Should be an assert? is it developers fault to Reset Guarded
+        // value?
+        specific->guardKey = boost::optional<pthread_key_t>();
+
+        InternalDestroy(specific);
+
+        int result = pthread_setspecific(m_key, NULL);
+
+        Assert(result == 0 &&
+               "Failed to reset thread local variable");
+    }
+
+    // GuardValue(true) allows to defer destroy (by pthread internal
+    // functionality) thread specific value until GuardValue(false) will be
+    // called.
+    void GuardValue(bool guard)
+    {
+        ManagedValue *instance =
+            static_cast<ManagedValue *>(pthread_getspecific(m_key));
+
+        Assert(instance && "Failed to get the value");
+
+        instance->guardKey = guard ? m_key : boost::optional<pthread_key_t>();
+    }
+};
+} // namespace DPL
+
+#endif // DPL_THREAD_H
diff --git a/commons/modules/core/include/dpl/type_list.h b/commons/modules/core/include/dpl/type_list.h
new file mode 100644 (file)
index 0000000..88afaf2
--- /dev/null
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        type_list.h
+ * @author      Bartosz Janiak (b.janiak@samsung.com)
+ * @version     1.0
+ * @brief       Generic type list template
+ */
+#ifndef DPL_TYPE_LIST_H
+#define DPL_TYPE_LIST_H
+
+#include <cstddef>
+
+namespace DPL {
+class TypeListGuard
+{
+  public:
+    template<size_t Index>
+    struct Element
+    {
+        struct ERROR_TypeListElementIndexIsOutOfBounds;
+        typedef ERROR_TypeListElementIndexIsOutOfBounds Type;
+    };
+
+    static const size_t Size = 0;
+};
+
+template<typename HeadType, typename TailType>
+class TypeList
+{
+  private:
+    class DummyClass
+    {};
+
+    template<typename List, size_t Enum>
+    struct TypeCounter : public TypeCounter<typename List::Tail, Enum + 1>
+    {};
+
+    template<size_t Enum>
+    struct TypeCounter<TypeListGuard, Enum>
+    {
+        static const size_t Size = Enum;
+    };
+
+  public:
+    typedef TailType Tail;
+    typedef HeadType Head;
+    typedef TypeList<HeadType, TailType> ThisType;
+
+    template<size_t Index, typename DummyType = DummyClass>
+    struct Element
+    {
+        typedef typename TailType::template Element<Index - 1>::Type Type;
+    };
+
+    template<typename DummyType>
+    struct Element<0, DummyType>
+    {
+        typedef HeadType Type;
+    };
+
+    template<typename Type, typename DummyType = DummyClass>
+    struct Contains
+    {
+        typedef typename TailType::template Contains<Type>::Yes Yes;
+    };
+
+    template<typename DummyType>
+    struct Contains<HeadType, DummyType>
+    {
+        typedef int Yes;
+    };
+
+    static const size_t Size = TypeCounter<ThisType, 0>::Size;
+};
+
+template<typename T1 = TypeListGuard, typename T2 = TypeListGuard,
+         typename T3 = TypeListGuard, typename T4 = TypeListGuard,
+         typename T5 = TypeListGuard, typename T6 = TypeListGuard,
+         typename T7 = TypeListGuard, typename T8 = TypeListGuard,
+         typename T9 = TypeListGuard, typename T10 = TypeListGuard,
+         typename T11 = TypeListGuard, typename T12 = TypeListGuard,
+         typename T13 = TypeListGuard, typename T14 = TypeListGuard,
+         typename T15 = TypeListGuard, typename T16 = TypeListGuard,
+         typename T17 = TypeListGuard, typename T18 = TypeListGuard,
+         typename T19 = TypeListGuard, typename T20 = TypeListGuard,
+         typename T21 = TypeListGuard, typename T22 = TypeListGuard,
+         typename T23 = TypeListGuard, typename T24 = TypeListGuard,
+         typename T25 = TypeListGuard, typename T26 = TypeListGuard,
+         typename T27 = TypeListGuard, typename T28 = TypeListGuard,
+         typename T29 = TypeListGuard, typename T30 = TypeListGuard,
+         typename T31 = TypeListGuard, typename T32 = TypeListGuard,
+         typename T33 = TypeListGuard, typename T34 = TypeListGuard,
+         typename T35 = TypeListGuard, typename T36 = TypeListGuard,
+         typename T37 = TypeListGuard, typename T38 = TypeListGuard,
+         typename T39 = TypeListGuard, typename T40 = TypeListGuard,
+         typename T41 = TypeListGuard, typename T42 = TypeListGuard,
+         typename T43 = TypeListGuard, typename T44 = TypeListGuard,
+         typename T45 = TypeListGuard, typename T46 = TypeListGuard,
+         typename T47 = TypeListGuard, typename T48 = TypeListGuard,
+         typename T49 = TypeListGuard, typename T50 = TypeListGuard,
+         typename T51 = TypeListGuard, typename T52 = TypeListGuard,
+         typename T53 = TypeListGuard, typename T54 = TypeListGuard,
+         typename T55 = TypeListGuard, typename T56 = TypeListGuard,
+         typename T57 = TypeListGuard, typename T58 = TypeListGuard,
+         typename T59 = TypeListGuard, typename T60 = TypeListGuard,
+         typename T61 = TypeListGuard, typename T62 = TypeListGuard,
+         typename T63 = TypeListGuard, typename T64 = TypeListGuard>
+struct TypeListDecl
+{
+    typedef TypeList<T1,
+                     typename TypeListDecl<
+                         T2, T3, T4, T5, T6, T7, T8,
+                         T9, T10, T11, T12, T13, T14, T15,
+                         T16, T17, T18, T19, T20, T21, T22,
+                         T23, T24, T25, T26, T27, T28, T29,
+                         T30, T31, T32, T33, T34, T35, T36,
+                         T37, T38, T39, T40, T41, T42, T43,
+                         T44, T45, T46, T47, T48, T49, T50,
+                         T51, T52, T53, T54, T55, T56, T57,
+                         T58, T59, T60, T61, T62, T63, T64>::Type> Type;
+};
+
+template<>
+struct TypeListDecl<TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard>
+{
+    typedef TypeListGuard Type;
+};
+} // namespace DPL
+
+#endif // DPL_TYPE_LIST_H
diff --git a/commons/modules/core/include/dpl/waitable_event.h b/commons/modules/core/include/dpl/waitable_event.h
new file mode 100644 (file)
index 0000000..364bc5c
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        waitable_event.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of waitable event
+ */
+#ifndef DPL_WAITABLE_EVENT_H
+#define DPL_WAITABLE_EVENT_H
+
+#include <dpl/waitable_handle.h>
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <vector>
+
+namespace DPL {
+class WaitableEvent :
+    private Noncopyable
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, CreateFailed)
+        DECLARE_EXCEPTION_TYPE(Base, DestroyFailed)
+        DECLARE_EXCEPTION_TYPE(Base, SignalFailed)
+        DECLARE_EXCEPTION_TYPE(Base, ResetFailed)
+    };
+
+  private:
+    int m_pipe[2];
+
+  public:
+    WaitableEvent();
+    virtual ~WaitableEvent();
+
+    WaitableHandle GetHandle() const;
+
+    void Signal() const;
+    void Reset() const;
+};
+} // namespace DPL
+
+#endif // DPL_WAITABLE_EVENT_H
diff --git a/commons/modules/core/include/dpl/waitable_handle.h b/commons/modules/core/include/dpl/waitable_handle.h
new file mode 100644 (file)
index 0000000..9864f78
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        waitable_handle.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the header file of waitable handle
+ */
+#ifndef DPL_WAITABLE_HANDLE_H
+#define DPL_WAITABLE_HANDLE_H
+
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <vector>
+
+namespace DPL {
+/**
+ * Waitable unix wait handle definition
+ */
+typedef int WaitableHandle;
+
+/**
+ * Waitable handle list
+ */
+typedef std::vector<WaitableHandle> WaitableHandleList;
+
+/**
+ * Wait mode
+ */
+class WaitMode
+{
+  public:
+    enum Type
+    {
+        Read,  ///< Wait for readability state changes
+        Write  ///< Wait for writability state changes
+    };
+};
+
+/**
+ * Waitable handle list ex
+ */
+typedef std::vector<std::pair<WaitableHandle,
+                              WaitMode::Type> > WaitableHandleListEx;
+
+/**
+ * Waitable handle index list
+ */
+typedef std::vector<size_t> WaitableHandleIndexList;
+
+/**
+ * Wait exceptions
+ */
+DECLARE_EXCEPTION_TYPE(DPL::Exception, WaitFailed)
+
+/**
+ * Wait for single handle readability
+ * Convience function.
+ *
+ * @return Signaled waitable handle index list
+ * @throw WaitFailed Fatal error occurred while waiting for signal
+ */
+WaitableHandleIndexList WaitForSingleHandle(
+    WaitableHandle handle,
+    unsigned long miliseconds =
+        0xFFFFFFFF);
+
+/**
+ * Wait for single handle
+ * Convience function.
+ *
+ * @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);
+
+/**
+ * Wait for multiple handles readability
+ *
+ * @return Signaled waitable handle index list
+ * @throw WaitFailed Fatal error occurred while waiting for signal
+ */
+WaitableHandleIndexList WaitForMultipleHandles(
+    const WaitableHandleList &handleList,
+    unsigned long miliseconds = 0xFFFFFFFF);
+
+/**
+ * Wait for multiple handles readability
+ *
+ * @return Signaled waitable handle index list
+ * @throw WaitFailed Fatal error occurred while waiting for signal
+ */
+WaitableHandleIndexList WaitForMultipleHandles(
+    const WaitableHandleListEx &handleListEx,
+    unsigned long miliseconds = 0xFFFFFFFF);
+} // namespace DPL
+
+#endif // DPL_WAITABLE_HANDLE_H
diff --git a/commons/modules/core/include/dpl/waitable_handle_watch_support.h b/commons/modules/core/include/dpl/waitable_handle_watch_support.h
new file mode 100644 (file)
index 0000000..644799c
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        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
+ */
+#ifndef DPL_WAITABLE_HANDLE_WATCH_SUPPORT_H
+#define DPL_WAITABLE_HANDLE_WATCH_SUPPORT_H
+
+#include <dpl/waitable_event.h>
+#include <dpl/waitable_handle.h>
+#include <dpl/exception.h>
+#include <list>
+#include <map>
+#include <mutex>
+
+namespace DPL {
+class Thread;
+
+class WaitableHandleWatchSupport
+{
+  public:
+    class WaitableHandleListener
+    {
+      public:
+        virtual ~WaitableHandleListener() {}
+
+        virtual void OnWaitableHandleEvent(WaitableHandle waitableHandle,
+                                           WaitMode::Type mode) = 0;
+    };
+
+  protected:
+    // Invoker waitable handle
+    // Signaled by Add/Remove methods
+    // After being signaled one must call Handle invoke to reset invoker
+    WaitableHandle WaitableInvokerHandle() const;
+
+    // Waitable handle ex list
+    WaitableHandleListEx WaitableWatcherHandles() const;
+
+    // Perform actions for signaled waitable handle
+    // Called in execution context, after
+    void HandleWatcher(WaitableHandle waitableHandle, WaitMode::Type mode);
+
+    // Perform actions after invoker was signaled
+    void InvokerFinished();
+
+    // Get invoker context
+    virtual Thread *GetInvokerThread() = 0;
+
+    // Invoke direct invoker
+    virtual void HandleDirectInvoker() = 0;
+
+  private:
+    // Waitable event watchers
+    struct WaitableHandleWatcher
+    {
+        WaitableHandleListener *listener;
+        WaitMode::Type mode;
+
+        WaitableHandleWatcher(WaitableHandleListener *l, WaitMode::Type m) :
+            listener(l),
+            mode(m)
+        {}
+    };
+
+    typedef std::list<WaitableHandleWatcher> WaitableHandleListenerList;
+
+    struct WaitableHandleWatchers
+    {
+        WaitableHandleListenerList listeners;
+        size_t readListenersCount;
+        size_t writeListenersCount;
+
+        WaitableHandleWatchers() :
+            readListenersCount(0),
+            writeListenersCount(0)
+        {}
+    };
+
+    typedef std::map<WaitableHandle,
+                     WaitableHandleWatchers> WaitableHandleWatchersMap;
+
+    // Waitable event watch support
+    mutable std::recursive_mutex m_watchersMutex;
+    WaitableHandleWatchersMap m_watchersMap;
+    WaitableEvent m_watchersInvoker;
+    WaitableEvent m_watchersInvokerCommit;
+
+    // Invoke call
+    void CommitInvoker();
+
+  public:
+    /**
+     * Constructor
+     */
+    explicit WaitableHandleWatchSupport();
+
+    /**
+     * Destructor
+     */
+    virtual ~WaitableHandleWatchSupport();
+
+    /**
+     * Adds listener for specific waitable event
+     *
+     * @param[in] listener Listener to attach
+     * @param[in] waitableHandle Waitable handle to listen for changes
+     * @param[in] mode Type of changes to listen to
+     * @return none
+     * @see WaitMode::Type
+     */
+    void AddWaitableHandleWatch(WaitableHandleListener *listener,
+                                WaitableHandle waitableHandle,
+                                WaitMode::Type mode);
+
+    /**
+     * Remove listener for specific waitable event
+     *
+     * @param[in] listener Listener to detach
+     * @param[in] waitableHandle Waitable handle to unlisten for changes
+     * @param[in] mode Type of changes to unlisten to
+     * @return none
+     * @see WaitMode::Type
+     */
+    void RemoveWaitableHandleWatch(WaitableHandleListener *listener,
+                                   WaitableHandle waitableHandle,
+                                   WaitMode::Type mode);
+
+    /**
+     * Retrieve inherited context
+     *
+     * @return Inherited waitable handle watch support
+     */
+    static WaitableHandleWatchSupport *InheritedContext();
+};
+} // namespace DPL
+
+#endif // DPL_WAITABLE_HANDLE_WATCH_SUPPORT_H
diff --git a/commons/modules/core/include/dpl/workaround.h b/commons/modules/core/include/dpl/workaround.h
new file mode 100644 (file)
index 0000000..19c26ef
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        workaround.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the header file of workaround
+ */
+#ifndef DPL_WORKAROUND_H
+#define DPL_WORKAROUND_H
+
+/**
+ * Define following macro to track invalid waitable handles
+ * in WaitForSingle/WaitForMultiple functions
+ */
+#define DPL_ENABLE_WAITABLE_HANDLE_BADF_CHECK
+
+/**
+ * Define following macro to enable workaround for problem
+ * with GLIB loop integration and EBADF error handling
+ */
+#define DPL_ENABLE_GLIB_LOOP_INTEGRATION_WORKAROUND
+
+/**
+ * Define following macro to enable workaround for problem
+ * with invalid conversions in htons/ntohs macros
+ */
+#define DPL_ENABLE_HTONS_NTOHS_I386_WORKAROUND
+
+#endif // DPL_WORKAROUND_H
diff --git a/commons/modules/core/src/DESCRIPTION b/commons/modules/core/src/DESCRIPTION
new file mode 100644 (file)
index 0000000..9043c93
--- /dev/null
@@ -0,0 +1 @@
+Source files
diff --git a/commons/modules/core/src/assert.cpp b/commons/modules/core/src/assert.cpp
new file mode 100644 (file)
index 0000000..5a18977
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        assert.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of assert
+ */
+#include <stdio.h>
+#include <stddef.h>
+#include <dpl/assert.h>
+#include <dpl/colors.h>
+#include <dpl/log/log.h>
+#include <cstdlib>
+
+namespace DPL {
+void AssertProc(const char *condition,
+                const char *file,
+                int line,
+                const char *function)
+{
+#define INTERNAL_LOG(message)                                          \
+    do                                                                 \
+    {                                                                  \
+        std::ostringstream platformLog;                                \
+        platformLog << message;                                        \
+        DPL::Log::LogSystemSingleton::Instance().Pedantic(             \
+            platformLog.str().c_str(),                                 \
+            __FILE__, __LINE__, __FUNCTION__);                         \
+    } \
+    while (0)
+
+    // Try to log failed assertion to log system
+    Try
+    {
+        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) {
+        // Just ignore possible double errors
+    }
+
+    // print assertion message to stderr
+    fprintf(stderr, "Assert!! [%s:%s] %s\n", file, function, condition);
+
+    // Fail with c-library abort
+    abort();
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/colors.cpp b/commons/modules/core/src/colors.cpp
new file mode 100644 (file)
index 0000000..0b2fcd4
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        colors.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       Some constants with definition of colors for Console
+ *              and html output
+ */
+#include <stddef.h>
+#include <dpl/colors.h>
+
+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";
+const char* RED_END = "\033[m";
+const char* PURPLE_BEGIN = "\033[0;35m";
+const char* PURPLE_END = "\033[m";
+const char* GREEN_BEGIN = "\033[0;32m";
+const char* GREEN_END = "\033[m";
+const char* CYAN_BEGIN = "\033[0;36m";
+const char* CYAN_END = "\033[m";
+const char* BOLD_RED_BEGIN = "\033[1;31m";
+const char* BOLD_RED_END = "\033[m";
+const char* BOLD_YELLOW_BEGIN = "\033[1;33m";
+const char* BOLD_YELLOW_END = "\033[m";
+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 {
+const char* BOLD_GREEN_BEGIN = "<font color=\"green\"><b>";
+const char* BOLD_GREEN_END = "</b></font>";
+const char* PURPLE_BEGIN = "<font color=\"purple\"><b>";
+const char* PURPLE_END = "</b></font>";
+const char* RED_BEGIN = "<font color=\"red\"><b>";
+const char* RED_END = "</b></font>";
+const char* GREEN_BEGIN = "<font color=\"green\">";
+const char* GREEN_END = "</font>";
+const char* CYAN_BEGIN = "<font color=\"cyan\">";
+const char* CYAN_END = "</font>";
+const char* BOLD_RED_BEGIN = "<font color=\"red\"><b>";
+const char* BOLD_RED_END = "</b></font>";
+const char* BOLD_YELLOW_BEGIN = "<font color=\"yellow\"><b>";
+const char* BOLD_YELLOW_END = "</b></font>";
+const char* BOLD_GOLD_BEGIN = "<font color=\"gold\"><b>";
+const char* BOLD_GOLD_END = "</b></font>";
+const char* BOLD_WHITE_BEGIN = "<font color=\"white\"><b>";
+const char* BOLD_WHITE_END = "</b></font>";
+} //namespace Html
+} //namespace Colors
+} //namespace DPL
diff --git a/commons/modules/core/src/errno_string.cpp b/commons/modules/core/src/errno_string.cpp
new file mode 100644 (file)
index 0000000..6c59776
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        errno_string.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of errno string
+ */
+#include <stddef.h>
+#include <dpl/errno_string.h>
+#include <dpl/assert.h>
+#include <dpl/exception.h>
+#include <dpl/assert.h>
+#include <dpl/free_deleter.h>
+#include <memory>
+#include <string>
+#include <cstddef>
+#include <cstring>
+#include <malloc.h>
+#include <cerrno>
+#include <stdexcept>
+
+namespace DPL {
+namespace // anonymous
+{
+const size_t DEFAULT_ERRNO_STRING_SIZE = 32;
+} // namespace anonymous
+
+std::string GetErrnoString(int error)
+{
+    size_t size = DEFAULT_ERRNO_STRING_SIZE;
+    char *buffer = NULL;
+
+    for (;;) {
+        // Add one extra characted for end of string null value
+        char *newBuffer = static_cast<char *>(::realloc(buffer, size + 1));
+
+        if (!newBuffer) {
+            // Failed to realloc
+            ::free(buffer);
+            throw std::bad_alloc();
+        }
+
+        // Setup reallocated buffer
+        buffer = newBuffer;
+        ::memset(buffer, 0, size + 1);
+
+        // Try to retrieve error string
+#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) {
+            std::unique_ptr<char[],free_deleter> scopedBufferFree(buffer);
+            return std::string(buffer);
+        }
+#else
+        errno = 0;
+
+        // Otherwise, the GNU-specific version is provided.
+        char *result = ::strerror_r(error, buffer, size);
+
+        if (result != NULL) {
+            std::unique_ptr<char[],free_deleter> scopedBufferFree(buffer);
+            return std::string(result);
+        }
+#endif
+
+        // Interpret errors
+        switch (errno) {
+        case EINVAL:
+            // We got an invalid errno value
+                ::free(buffer);
+            ThrowMsg(InvalidErrnoValue, "Invalid errno value: " << error);
+
+        case ERANGE:
+            // Incease buffer size and retry
+            size <<= 1;
+            continue;
+
+        default:
+            AssertMsg(0, "Invalid errno value after call to strerror_r!");
+        }
+    }
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/exception.cpp b/commons/modules/core/src/exception.cpp
new file mode 100644 (file)
index 0000000..d3673e6
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        exception.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation of exception system
+ */
+#include <stddef.h>
+#include <dpl/exception.h>
+#include <dpl/log/log.h>
+#include <cstdio>
+
+namespace DPL {
+Exception* Exception::m_lastException = NULL;
+unsigned int Exception::m_exceptionCount = 0;
+void (*Exception::m_terminateHandler)() = NULL;
+
+void LogUnhandledException(const std::string &str)
+{
+    // Logging to console
+    printf("%s\n", str.c_str());
+
+    // Logging to dlog
+    LogPedantic(str);
+}
+
+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 << str;
+    printf("%s\n", msg.str().c_str());
+
+    // Logging to dlog
+    DPL::Log::LogSystemSingleton::Instance().Error(
+        str.c_str(), filename, line, function);
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/mutex.cpp b/commons/modules/core/src/mutex.cpp
new file mode 100644 (file)
index 0000000..eed1f2e
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        mutex.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of mutex
+ */
+#include <stddef.h>
+#include <dpl/mutex.h>
+#include <dpl/assert.h>
+#include <dpl/log/log.h>
+#include <errno.h>
+
+namespace DPL {
+Mutex::Mutex()
+{
+    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);
+    }
+}
+
+Mutex::~Mutex()
+{
+    if (pthread_mutex_destroy(&m_mutex) != 0) {
+        int error = errno;
+
+        LogPedantic("Failed to destroy mutex. Errno: " << error);
+    }
+}
+
+void Mutex::Lock() const
+{
+    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);
+    }
+}
+
+void Mutex::Unlock() const
+{
+    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);
+    }
+}
+
+Mutex::ScopedLock::ScopedLock(Mutex *mutex) :
+    m_mutex(mutex)
+{
+    Assert(mutex != NULL);
+    m_mutex->Lock();
+}
+
+Mutex::ScopedLock::~ScopedLock()
+{
+    Try
+    {
+        m_mutex->Unlock();
+    }
+    Catch(Mutex::Exception::UnlockFailed)
+    {
+        LogPedantic("Failed to leave mutex scoped lock");
+    }
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/noncopyable.cpp b/commons/modules/core/src/noncopyable.cpp
new file mode 100644 (file)
index 0000000..9453655
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        noncopyable.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of noncopyable
+ */
+#include <stddef.h>
+#include <dpl/noncopyable.h>
+
+namespace DPL {
+Noncopyable::Noncopyable()
+{}
+
+Noncopyable::~Noncopyable()
+{}
+} // namespace DPL
diff --git a/commons/modules/core/src/recursive_mutex.cpp b/commons/modules/core/src/recursive_mutex.cpp
new file mode 100644 (file)
index 0000000..234d25f
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        recursive_mutex.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of recursive mutex
+ */
+#include <stddef.h>
+#include <dpl/recursive_mutex.h>
+#include <dpl/assert.h>
+
+namespace DPL {
+RecursiveMutex::RecursiveMutex()
+{
+    pthread_mutexattr_t attr;
+
+    pthread_mutexattr_init(&attr);
+    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
+
+    if (pthread_mutex_init(&m_mutex, &attr) != 0) {
+        Throw(Exception::CreateFailed);
+    }
+}
+
+RecursiveMutex::~RecursiveMutex()
+{
+    if (pthread_mutex_destroy(&m_mutex) != 0) {
+        Throw(Exception::DestroyFailed);
+    }
+}
+
+void RecursiveMutex::Lock() const
+{
+    if (pthread_mutex_lock(&m_mutex) != 0) {
+        Throw(Exception::LockFailed);
+    }
+}
+
+void RecursiveMutex::Unlock() const
+{
+    if (pthread_mutex_unlock(&m_mutex) != 0) {
+        Throw(Exception::UnlockFailed);
+    }
+}
+
+RecursiveMutex::ScopedLock::ScopedLock(RecursiveMutex *mutex) :
+    m_mutex(mutex)
+{
+    Assert(mutex != NULL);
+    m_mutex->Lock();
+}
+
+RecursiveMutex::ScopedLock::~ScopedLock()
+{
+    m_mutex->Unlock();
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/serialization.cpp b/commons/modules/core/src/serialization.cpp
new file mode 100644 (file)
index 0000000..f8f05ff
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        serialization.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of data serialization.
+ */
+#include <stddef.h>
+#include <dpl/serialization.h>
+
+//
+// Note:
+//
+// The file here is left blank to enable precompilation
+// of templates in corresponding header file.
+// Do not remove this file.
+//
diff --git a/commons/modules/core/src/single_instance.cpp b/commons/modules/core/src/single_instance.cpp
new file mode 100644 (file)
index 0000000..274b5f8
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        single_instance.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of single instance
+ */
+#include <stddef.h>
+#include <dpl/single_instance.h>
+#include <dpl/log/log.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <dpl/assert.h>
+
+namespace DPL {
+namespace // anonumous
+{
+const char *LOCK_PREFIX_PATH = "/tmp/dpl_single_instance_";
+}
+SingleInstance::SingleInstance() :
+    m_locked(false),
+    m_fdLock(-1)
+{}
+
+SingleInstance::~SingleInstance()
+{
+    AssertMsg(!m_locked, "Single instance must be released before exit!");
+}
+
+bool SingleInstance::TryLock(const std::string &lockName)
+{
+    LogPedantic("Locking single instance: " << lockName);
+
+    struct flock lock;
+
+    lock.l_type = F_WRLCK;
+    lock.l_whence = SEEK_SET;
+    lock.l_start = 0;
+    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));
+
+    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) {
+        LogPedantic("Instance locked: " << lockName);
+
+        // It is locked now
+        m_locked = true;
+
+        // Done
+        return true;
+    }
+
+    if (errno == EACCES || errno == EAGAIN) {
+        LogPedantic("Instance is already running: " << lockName);
+        return false;
+    }
+
+    // This is lock error
+    ThrowMsg(Exception::LockError, "Cannot lock single instance lock file!");
+}
+
+void SingleInstance::Release()
+{
+    if (!m_locked) {
+        return;
+    }
+
+    LogPedantic("Unlocking single instance");
+
+    // Unlock file
+    struct flock lock;
+
+    lock.l_type = F_UNLCK;
+    lock.l_whence = SEEK_SET;
+    lock.l_start = 0;
+    lock.l_len = 1;
+
+    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!");
+    }
+
+    // Close lock file
+    if (TEMP_FAILURE_RETRY(close(m_fdLock)) == -1) {
+        ThrowMsg(Exception::LockError,
+                 "Cannot close single instance lock file!");
+    }
+
+    m_fdLock = -1;
+
+    // Done
+    m_locked = false;
+    LogPedantic("Instance unlocked");
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/singleton.cpp b/commons/modules/core/src/singleton.cpp
new file mode 100644 (file)
index 0000000..a76e8ac
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        generic_event.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#include <stddef.h>
+#include <dpl/singleton.h>
+
+//
+// Note:
+//
+// The file here is left blank to enable precompilation
+// of templates in corresponding header file.
+// Do not remove this file.
+//
diff --git a/commons/modules/core/src/string.cpp b/commons/modules/core/src/string.cpp
new file mode 100644 (file)
index 0000000..a642eaa
--- /dev/null
@@ -0,0 +1,250 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        string.cpp
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ */
+#include <stddef.h>
+#include <memory>
+#include <dpl/string.h>
+#include <dpl/char_traits.h>
+#include <dpl/errno_string.h>
+#include <dpl/exception.h>
+#include <dpl/log/log.h>
+#include <string>
+#include <vector>
+#include <algorithm>
+#include <cstring>
+#include <errno.h>
+#include <iconv.h>
+#include <unicode/ustring.h>
+
+// TODO: Completely move to ICU
+namespace DPL {
+namespace //anonymous
+{
+class ASCIIValidator
+{
+    const std::string& m_TestedString;
+
+  public:
+    ASCIIValidator(const std::string& aTestedString);
+
+    void operator()(char aCharacter) const;
+};
+
+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<int>(aCharacter)
+                                      << " from string [" <<
+            m_TestedString
+                                      << "] passed as ASCII");
+    }
+}
+
+const iconv_t gc_IconvOperError = reinterpret_cast<iconv_t>(-1);
+const size_t gc_IconvConvertError = static_cast<size_t>(-1);
+} // namespace anonymous
+
+String FromUTF8String(const std::string& aIn)
+{
+    if (aIn.empty()) {
+        return String();
+    }
+
+    size_t inbytes = aIn.size();
+
+    // Default iconv UTF-32 module adds BOM (4 bytes) in from of string
+    // The worst case is when 8bit UTF-8 char converts to 32bit UTF-32
+    // newsize = oldsize * 4 + end + bom
+    // newsize - bytes for UTF-32 string
+    // 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);
+    std::vector<wchar_t> output(inbytes + 2, 0);
+
+    size_t outbytesleft = outbytes;
+    char* inbuf = const_cast<char*>(aIn.c_str());
+
+    // vector is used to provide buffer for iconv which expects char* buffer
+    // but during conversion from UTF32 uses internaly wchar_t
+    char* outbuf = reinterpret_cast<char*>(&output[0]);
+
+    iconv_t iconvHandle = iconv_open("UTF-32", "UTF-8");
+
+    if (gc_IconvOperError == iconvHandle) {
+        int error = errno;
+
+        ThrowMsg(StringException::IconvInitErrorUTF8ToUTF32,
+                 "iconv_open failed for " << "UTF-32 <- UTF-8" <<
+                 "error: " << GetErrnoString(error));
+    }
+
+    size_t iconvRet = iconv(iconvHandle,
+                            &inbuf,
+                            &inbytes,
+                            &outbuf,
+                            &outbytesleft);
+
+    iconv_close(iconvHandle);
+
+    if (gc_IconvConvertError == iconvRet) {
+        ThrowMsg(StringException::IconvConvertErrorUTF8ToUTF32,
+                 "iconv failed for " << "UTF-32 <- UTF-8" << "error: "
+                                     << GetErrnoString());
+    }
+
+    // Ignore BOM in front of UTF-32
+    return &output[1];
+}
+
+std::string ToUTF8String(const DPL::String& aIn)
+{
+    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<char*>(const_cast<wchar_t*>(aIn.c_str()));
+    std::vector<char> output(inbytes, 0);
+    char* outbuf = &output[0];
+
+    size_t outbytesleft = outbytes;
+
+    iconv_t iconvHandle = iconv_open("UTF-8", "UTF-32");
+
+    if (gc_IconvOperError == iconvHandle) {
+        ThrowMsg(StringException::IconvInitErrorUTF32ToUTF8,
+                 "iconv_open failed for " << "UTF-8 <- UTF-32"
+                                          << "error: " << GetErrnoString());
+    }
+
+    size_t iconvRet = iconv(iconvHandle,
+                            &inbuf,
+                            &inbytes,
+                            &outbuf,
+                            &outbytesleft);
+
+    iconv_close(iconvHandle);
+
+    if (gc_IconvConvertError == iconvRet) {
+        ThrowMsg(StringException::IconvConvertErrorUTF32ToUTF8,
+                 "iconv failed for " << "UTF-8 <- UTF-32"
+                                     << "error: " << GetErrnoString());
+    }
+
+    return &output[0];
+}
+
+String FromASCIIString(const std::string& aString)
+{
+    String output;
+
+    std::for_each(aString.begin(), aString.end(), ASCIIValidator(aString));
+    std::copy(aString.begin(), aString.end(), std::back_inserter<String>(output));
+
+    return output;
+}
+
+String FromUTF32String(const std::wstring& aString)
+{
+    return String(&aString[0]);
+}
+
+static UChar *ConvertToICU(const String &inputString)
+{
+    std::unique_ptr<UChar[]> outputString;
+    int32_t size = 0;
+    int32_t convertedSize = 0;
+    UErrorCode error = U_ZERO_ERROR;
+
+    // Calculate size of output string
+    ::u_strFromWCS(NULL,
+                   0,
+                   &size,
+                   inputString.c_str(),
+                   -1,
+                   &error);
+
+    if (error == U_ZERO_ERROR ||
+        error == U_BUFFER_OVERFLOW_ERROR)
+    {
+        // What buffer size is ok ?
+        LogPedantic("ICU: Output buffer size: " << size);
+    } else {
+        ThrowMsg(StringException::ICUInvalidCharacterFound,
+                 "ICU: Failed to retrieve output string size. Error: "
+                 << error);
+    }
+
+    // Allocate proper buffer
+    outputString.reset(new UChar[size + 1]);
+    ::memset(outputString.get(), 0, sizeof(UChar) * (size + 1));
+
+    error = U_ZERO_ERROR;
+
+    // Do conversion
+    ::u_strFromWCS(outputString.get(),
+                   size + 1,
+                   &convertedSize,
+                   inputString.c_str(),
+                   -1,
+                   &error);
+
+    if (!U_SUCCESS(error)) {
+        ThrowMsg(StringException::ICUInvalidCharacterFound,
+                 "ICU: Failed to convert string. Error: " << error);
+    }
+
+    // Done
+    return outputString.release();
+}
+
+int StringCompare(const String &left,
+                  const String &right,
+                  bool caseInsensitive)
+{
+    // Convert input strings
+    std::unique_ptr<UChar[]> leftICU(ConvertToICU(left));
+    std::unique_ptr<UChar[]> rightICU(ConvertToICU(right));
+
+    if (caseInsensitive) {
+        return static_cast<int>(u_strcasecmp(leftICU.get(), rightICU.get(), 0));
+    } else {
+        return static_cast<int>(u_strcmp(leftICU.get(), rightICU.get()));
+    }
+}
+} //namespace DPL
+
+std::ostream& operator<<(std::ostream& aStream, const DPL::String& aString)
+{
+    return aStream << DPL::ToUTF8String(aString);
+}
diff --git a/commons/modules/core/src/thread.cpp b/commons/modules/core/src/thread.cpp
new file mode 100644 (file)
index 0000000..e033580
--- /dev/null
@@ -0,0 +1,617 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        thread.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of thread
+ */
+#include <stddef.h>
+#include <dpl/thread.h>
+#include <dpl/log/log.h>
+#include <sys/time.h>
+#include <algorithm>
+#include <dpl/assert.h>
+#include <errno.h>
+#include <time.h>
+#include <string.h>
+
+namespace // anonymous
+{
+static const size_t NANOSECONDS_PER_SECOND =
+    static_cast<uint64_t>(1000 * 1000 * 1000);
+
+static const size_t NANOSECONDS_PER_MILISECOND =
+    static_cast<uint64_t>(1000 * 1000);
+
+static const size_t NANOSECONDS_PER_MICROSECOND =
+    static_cast<uint64_t>(1000);
+
+static const std::thread::id g_mainThread = std::this_thread::get_id();
+
+class ThreadSpecific
+{
+  public:
+    pthread_key_t threadSpecific;
+
+    ThreadSpecific() :
+        threadSpecific(0)
+    {
+        threadSpecific = 0;
+        pthread_key_create(&threadSpecific, NULL);
+    }
+
+    virtual ~ThreadSpecific()
+    {
+        pthread_key_delete(threadSpecific);
+    }
+};
+
+static ThreadSpecific g_threadSpecific;
+} // namespace anonymous
+
+namespace DPL {
+bool g_TLSforMainCreated = false;
+
+Thread::Thread() :
+    m_thread(),
+    m_abandon(false),
+    m_running(false),
+    m_directInvoke(false)
+{}
+
+Thread::~Thread()
+{
+    // Ensure that we quit thread
+    // Always wait thread by yourself; if thread is still running
+    // this may be sometimes very bad. When derived, some resources
+    // may leak or be doubly freed
+    Quit();
+
+    // Remove any remainig events
+    // Thread proc is surely not running now
+    for (InternalEventList::iterator iterator = m_eventList.begin();
+         iterator != m_eventList.end();
+         ++iterator)
+    {
+        iterator->eventDeleteProc(iterator->event, iterator->userParam);
+    }
+
+    m_eventList.clear();
+}
+
+bool Thread::IsMainThread()
+{
+    return (std::this_thread::get_id() == g_mainThread);
+}
+
+Thread *Thread::GetCurrentThread()
+{
+    if (std::this_thread::get_id() == g_mainThread) {
+        return NULL;
+    }
+
+    void *threadSpecific = pthread_getspecific(g_threadSpecific.threadSpecific);
+
+    // Is this a managed thread ?
+    if (threadSpecific == NULL) {
+        Throw(Exception::UnmanagedThread);
+    }
+
+    return static_cast<Thread *>(threadSpecific);
+}
+
+void *Thread::StaticThreadEntry(void *param)
+{
+    LogPedantic("Entered static thread entry");
+
+    // Retrieve context
+    Thread *This = static_cast<Thread *>(param);
+    Assert(This != NULL);
+
+    // Set thread specific
+    int result = pthread_setspecific(g_threadSpecific.threadSpecific, This);
+
+    if (result != 0) {
+        LogError("Failed to set threadSpecific. Error: " << strerror(result));
+    }
+
+    // Enter thread proc
+    // Do not allow exceptions to hit pthread core
+    UNHANDLED_EXCEPTION_HANDLER_BEGIN
+    {
+        This->ThreadEntry();
+    }
+    UNHANDLED_EXCEPTION_HANDLER_END
+
+    // Critical section
+    {
+        // Leave running state
+        std::lock_guard<std::mutex> lock(This->m_stateMutex);
+
+        This->m_running = false;
+
+        // Abandon thread
+        if (This->m_abandon) {
+            LogPedantic("Thread was abandoned");
+            This->m_thread.detach();
+        } else {
+            LogPedantic("Thread is joinable");
+        }
+    }
+
+    return NULL;
+}
+
+int Thread::ThreadEntry()
+{
+    LogPedantic("Entered default thread entry");
+    return Exec();
+}
+
+void Thread::ProcessEvents()
+{
+    LogPedantic("Processing events");
+
+    // Steal current event list
+    InternalEventList stolenEvents;
+
+    // Enter event list critical section
+    {
+        std::lock_guard<std::mutex> lock(m_eventMutex);
+        m_eventList.swap(stolenEvents);
+        m_eventInvoker.Reset();
+    }
+
+    // Process event list
+    LogPedantic("Stolen " << stolenEvents.size() << " internal events");
+
+    for (InternalEventList::iterator iterator = stolenEvents.begin();
+         iterator != stolenEvents.end();
+         ++iterator)
+    {
+        // Dispatch immediate event
+        iterator->eventDispatchProc(iterator->event, iterator->userParam);
+
+        // Delete event
+        iterator->eventDeleteProc(iterator->event, iterator->userParam);
+    }
+}
+
+void Thread::ProcessTimedEvents()
+{
+    // Critical section on timed events mutex
+    {
+        std::lock_guard<std::mutex> lock(m_timedEventMutex);
+
+        // Get current time
+        unsigned long currentTimeMiliseconds = GetCurrentTimeMiliseconds();
+
+        // Info
+        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)
+        {
+            // Info
+            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,
+                      m_timedEventVector.begin()->eventDispatchProc,
+                      m_timedEventVector.begin()->eventDeleteProc,
+                      m_timedEventVector.begin()->userParam);
+
+            // Remove timed eventand fix heap
+            std::pop_heap(m_timedEventVector.begin(), m_timedEventVector.end());
+            m_timedEventVector.pop_back();
+        }
+    }
+}
+
+unsigned long Thread::GetCurrentTimeMiliseconds() const
+{
+    timeval tv;
+    gettimeofday(&tv, NULL);
+    return static_cast<unsigned long>(tv.tv_sec) * 1000 +
+           static_cast<unsigned long>(tv.tv_usec) / 1000;
+}
+
+int Thread::Exec()
+{
+    LogPedantic("Executing thread event processing");
+
+    const std::size_t MIN_HANDLE_LIST_SIZE = 4;
+
+    // Start processing of events
+    WaitableHandleListEx handleList;
+
+    // index 0: Quit waitable event handle
+    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));
+
+    // index 2: Timed event occurred event handle
+    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));
+
+    //
+    // 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));
+    }
+
+    // Quit flag
+    bool quit = false;
+
+    while (!quit) {
+        // Retrieve minimum wait time, according to timed events list
+        unsigned long minimumWaitTime;
+
+        // Critical section on timed events mutex
+        {
+            std::lock_guard<std::mutex> lock(m_timedEventMutex);
+
+            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) {
+                    minimumWaitTime = 0;
+                } else {
+                    minimumWaitTime = destinationTimeMiliseconds -
+                        currentTimeMiliseconds;
+                }
+            } else {
+                minimumWaitTime = 0xFFFFFFFF; // Infinity
+            }
+        }
+
+        // Info
+        LogPedantic(
+            "Thread loop minimum wait time: " << minimumWaitTime << " ms");
+
+        // Do thread waiting
+        WaitableHandleIndexList waitableHandleIndexList =
+            WaitForMultipleHandles(handleList, minimumWaitTime);
+
+        if (waitableHandleIndexList.empty()) {
+            // Timeout occurred. Process timed events.
+            LogPedantic("Timed event list elapsed invoker");
+            ProcessTimedEvents();
+            continue;
+        }
+
+        // Go through each index
+        for (WaitableHandleIndexList::const_iterator
+             waitableHandleIndexIterator = waitableHandleIndexList.begin();
+             waitableHandleIndexIterator != waitableHandleIndexList.end();
+             ++waitableHandleIndexIterator)
+        {
+            size_t index = *waitableHandleIndexIterator;
+
+            LogPedantic("Event loop triggered with index: " << index);
+
+            switch (index) {
+            case 0:
+                // Quit waitable event handle
+                quit = true;
+                break;
+
+            case 1:
+                // Event occurred event handle
+                ProcessEvents();
+
+                // Handle direct invoker
+                if (m_directInvoke) {
+                    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));
+                    }
+                }
+
+                // Done
+                break;
+
+            case 2:
+                // Timed event list changed
+                LogPedantic("Timed event list changed invoker");
+                ProcessTimedEvents();
+
+                // Reset timed event invoker
+                m_timedEventInvoker.Reset();
+
+                // Done
+                break;
+
+            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();
+                }
+
+                // 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();
+
+                LogPedantic("Waitable handle watch invoker event handled");
+
+                // Done
+                break;
+
+            default:
+                // Waitable event watch list
+                LogPedantic("Waitable handle watch event occurred");
+
+                // Handle event in waitable handle watch
+                {
+                    std::pair<WaitableHandle,
+                              WaitMode::Type> 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();
+                    }
+
+                    // Insert current waitable event handles instead
+                    {
+                        WaitableHandleListEx waitableHandleWatchHandles =
+                            WaitableHandleWatchSupport::
+                                WaitableWatcherHandles();
+                        std::copy(waitableHandleWatchHandles.begin(),
+                                  waitableHandleWatchHandles.end(),
+                                  std::back_inserter(handleList));
+                    }
+                }
+
+                LogPedantic("Waitable handle watch event handled");
+
+                // Done
+                break;
+            }
+        }
+    }
+
+    LogPedantic("Leaving thread event processing");
+    return 0;
+}
+
+void Thread::Run()
+{
+    LogPedantic("Running thread");
+
+    // Critical section
+    {
+        std::lock_guard<std::mutex> lock(m_stateMutex);
+
+        if (m_running) {
+            return;
+        }
+
+        try{
+            m_thread = std::thread(StaticThreadEntry,this);
+        }catch(std::system_error e){
+            Throw(Exception::RunFailed);
+        }
+
+        // At default, we abandon thread
+        m_abandon = true;
+
+        // Enter running state
+        m_running = true;
+    }
+
+    LogPedantic("Thread run");
+}
+
+void Thread::Quit()
+{
+    // Critical section
+    {
+        std::lock_guard<std::mutex> lock(m_stateMutex);
+
+        // Is thread running ?
+        if (!m_running) {
+            return;
+        }
+
+        LogPedantic("Quitting thread...");
+
+        // Do not abandon thread, we will join
+        m_abandon = false;
+
+        // Singal quit waitable event
+        m_quitEvent.Signal();
+    }
+
+    try{
+        m_thread.join();
+    }catch(std::system_error e){
+        Throw(Exception::QuitFailed);
+    }
+
+    LogPedantic("Thread quit");
+}
+
+void Thread::PushEvent(void *event,
+                       EventDispatchProc eventDispatchProc,
+                       EventDeleteProc eventDeleteProc,
+                       void *userParam)
+{
+    // Enter event list critical section
+    std::lock_guard<std::mutex> lock(m_eventMutex);
+
+    // Push new event
+    m_eventList.push_back(InternalEvent(event, userParam, eventDispatchProc,
+                                        eventDeleteProc));
+
+    // Trigger invoker
+    m_eventInvoker.Signal();
+
+    LogPedantic("Event pushed and invoker signaled");
+}
+
+void Thread::PushTimedEvent(void *event,
+                            double dueTimeSeconds,
+                            EventDispatchProc eventDispatchProc,
+                            EventDeleteProc eventDeleteProc,
+                            void *userParam)
+{
+    // Check for developer errors
+    Assert(dueTimeSeconds >= 0.0);
+
+    // Enter timed event list critical section
+    std::lock_guard<std::mutex> lock(m_timedEventMutex);
+
+    // Get current time
+    unsigned long currentTimeMiliseconds = GetCurrentTimeMiliseconds();
+
+    // Convert to miliseconds
+    unsigned long dueTimeMiliseconds =
+        static_cast<unsigned long>(1000.0 * dueTimeSeconds);
+
+    // Push new timed event
+    m_timedEventVector.push_back(InternalTimedEvent(event, userParam,
+                                                    dueTimeMiliseconds,
+                                                    currentTimeMiliseconds,
+                                                    eventDispatchProc,
+                                                    eventDeleteProc));
+
+    // Heapify timed events
+    std::make_heap(m_timedEventVector.begin(), m_timedEventVector.end());
+
+    // Trigger invoker
+    m_timedEventInvoker.Signal();
+
+    LogPedantic(
+        "Timed event pushed and invoker signaled: due time: " <<
+        dueTimeMiliseconds << " ms, absolute due time: " <<
+        currentTimeMiliseconds + dueTimeMiliseconds << " ms");
+}
+
+Thread *Thread::GetInvokerThread()
+{
+    return this;
+}
+
+void Thread::HandleDirectInvoker()
+{
+    // We must be in ProcessEvents call stack
+    // Mark that situation to handle direct invoker
+    m_directInvoke = true;
+}
+
+void Thread::Sleep(uint64_t seconds)
+{
+    NanoSleep(seconds * NANOSECONDS_PER_SECOND);
+}
+
+void Thread::MiliSleep(uint64_t miliseconds)
+{
+    NanoSleep(miliseconds * NANOSECONDS_PER_MILISECOND);
+}
+
+void Thread::MicroSleep(uint64_t microseconds)
+{
+    NanoSleep(microseconds * NANOSECONDS_PER_MICROSECOND);
+}
+
+void Thread::NanoSleep(uint64_t nanoseconds)
+{
+    timespec requestedTime = {
+        static_cast<time_t>(
+            nanoseconds / NANOSECONDS_PER_SECOND),
+
+        static_cast<long>(
+            nanoseconds % NANOSECONDS_PER_SECOND)
+    };
+
+    timespec remainingTime;
+
+    for (;;) {
+        if (nanosleep(&requestedTime, &remainingTime) == 0) {
+            break;
+        }
+
+        int error = errno;
+        Assert(error == EINTR);
+
+        requestedTime = remainingTime;
+    }
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/waitable_event.cpp b/commons/modules/core/src/waitable_event.cpp
new file mode 100644 (file)
index 0000000..4808896
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        waitable_event.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of waitable event
+ */
+#include <stddef.h>
+#include <dpl/waitable_event.h>
+#include <sys/select.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <errno.h>
+
+namespace DPL {
+WaitableEvent::WaitableEvent()
+{
+    if (pipe(m_pipe) == -1) {
+        Throw(Exception::CreateFailed);
+    }
+
+    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) {
+        Throw(Exception::DestroyFailed);
+    }
+
+    if (TEMP_FAILURE_RETRY(close(m_pipe[1])) == -1) {
+        Throw(Exception::DestroyFailed);
+    }
+}
+
+WaitableHandle WaitableEvent::GetHandle() const
+{
+    return m_pipe[0];
+}
+
+void WaitableEvent::Signal() const
+{
+    char data = 0;
+
+    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) {
+        Throw(Exception::ResetFailed);
+    }
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/waitable_handle.cpp b/commons/modules/core/src/waitable_handle.cpp
new file mode 100644 (file)
index 0000000..5ea600d
--- /dev/null
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        waitable_handle.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of waitable handle
+ */
+#include <stddef.h>
+#include <dpl/waitable_event.h>
+#include <dpl/workaround.h>
+#include <dpl/log/log.h>
+#include <sys/select.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <dpl/assert.h>
+
+namespace DPL {
+namespace // anonymous
+{
+void CheckWaitableHandle(WaitableHandle handle)
+{
+#ifdef DPL_ENABLE_WAITABLE_HANDLE_BADF_CHECK
+    // Try to get descriptor flags
+    int result = fcntl(handle, F_GETFL);
+
+    if (result == -1 && errno == EBADF) {
+        AssertMsg(0, "CheckWaitableHandle: Invalid WaitableHandle! (EBADF)");
+    }
+
+    AssertMsg(result != -1, "CheckWaitableHandle: Invalid WaitableHandle!");
+#endif // DPL_ENABLE_WAITABLE_HANDLE_BADF_CHECK
+}
+} // namespace anonymous
+
+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)
+{
+    WaitableHandleListEx waitHandles;
+    waitHandles.push_back(std::make_pair(handle, mode));
+    return WaitForMultipleHandles(waitHandles, miliseconds);
+}
+
+WaitableHandleIndexList WaitForMultipleHandles(
+    const WaitableHandleList &waitableHandleList,
+    unsigned long miliseconds)
+{
+    WaitableHandleListEx handleList;
+
+    for (WaitableHandleList::const_iterator iterator = waitableHandleList.begin();
+         iterator != waitableHandleList.end();
+         ++iterator)
+    {
+        // Wait for multiple objects
+        handleList.push_back(std::make_pair(*iterator, WaitMode::Read));
+    }
+
+    // Do waiting
+    return WaitForMultipleHandles(handleList, miliseconds);
+}
+
+WaitableHandleIndexList WaitForMultipleHandles(
+    const WaitableHandleListEx &waitableHandleListEx,
+    unsigned long miliseconds)
+{
+    fd_set readFds, writeFds, errorFds;
+
+    // Fill sets
+    int maxFd = -1;
+
+    FD_ZERO(&readFds);
+    FD_ZERO(&writeFds);
+    FD_ZERO(&errorFds);
+
+    // Add read wait handles
+    for (WaitableHandleListEx::const_iterator iterator =
+             waitableHandleListEx.begin();
+         iterator != waitableHandleListEx.end();
+         ++iterator)
+    {
+        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) {
+            FD_SET(iterator->first, &readFds);
+        } else if (iterator->second == WaitMode::Write) {
+            FD_SET(iterator->first, &writeFds);
+        }
+    }
+
+    // Do select
+    timeval timeout;
+    timeval *effectiveTimeout = NULL;
+    if (miliseconds != 0xFFFFFFFF) {
+        timeout.tv_sec = miliseconds / 1000;
+        timeout.tv_usec = (miliseconds % 1000) * 1000;
+        effectiveTimeout = &timeout;
+    }
+
+    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();
+         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)) {
+                indexes.push_back(index);
+            }
+        } else if (iterator->second == WaitMode::Write) {
+            if (FD_ISSET(iterator->first, &writeFds)) {
+                indexes.push_back(index);
+            }
+        }
+        ++index;
+    }
+
+    // Successfuly awaited some events or timeout occurred
+    return indexes;
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/waitable_handle_watch_support.cpp b/commons/modules/core/src/waitable_handle_watch_support.cpp
new file mode 100644 (file)
index 0000000..70661b0
--- /dev/null
@@ -0,0 +1,394 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        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
+ */
+#include <stddef.h>
+#include <dpl/waitable_handle_watch_support.h>
+#include <dpl/thread.h>
+//#include <dpl/main.h>
+#include <dpl/log/log.h>
+#include <algorithm>
+#include <dpl/assert.h>
+
+namespace DPL {
+WaitableHandleWatchSupport::WaitableHandleWatchSupport()
+{}
+
+WaitableHandleWatchSupport::~WaitableHandleWatchSupport()
+{
+    // Developer assertions
+    if (!m_watchersMap.empty()) {
+        LogWarning("### Leaked watchers map dump ###");
+
+        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);
+
+            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);
+            }
+        }
+    }
+}
+
+WaitableHandle WaitableHandleWatchSupport::WaitableInvokerHandle() const
+{
+    return m_watchersInvoker.GetHandle();
+}
+
+WaitableHandleListEx WaitableHandleWatchSupport::WaitableWatcherHandles() const
+{
+    // Critical section
+    {
+        std::lock_guard<std::recursive_mutex> lock(m_watchersMutex);
+
+        WaitableHandleListEx handleList;
+
+        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.writeListenersCount > 0) {
+                handleList.push_back(std::make_pair(iterator->first,
+                                                    WaitMode::Write));
+            }
+        }
+
+        return handleList;
+    }
+}
+
+void WaitableHandleWatchSupport::InvokerFinished()
+{
+    LogPedantic("Invoker finished called");
+
+    // Reset invoker
+    m_watchersInvoker.Reset();
+
+    // Commit invoke
+    m_watchersInvokerCommit.Signal();
+}
+
+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!
+    //
+    LogPedantic("Waitable event occurred");
+
+    // Critical section for other threads
+    {
+        std::lock_guard<std::recursive_mutex> 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
+        //         during handler dispatch sequence is _not_ supported.
+        WaitableHandleWatchersMap trackedWatchers = m_watchersMap;
+
+        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())
+            {
+                LogPedantic("Watcher disappeared during watcher handler");
+                continue;
+            }
+
+            // Is this is a waitable handle that we are searching for ?
+            if (waitableHandle != trackedWatchersIterator->first) {
+                continue;
+            }
+
+            // Track watcher listeners list
+            WaitableHandleListenerList trackedListeners =
+                trackedWatchersIterator->second.listeners;
+
+            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.
+
+            // Call all waitable event listeners who listen for that event
+            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())
+                {
+                    LogPedantic("Watcher disappeared during watcher handler");
+                    break;
+                }
+
+                // Check if this watcher listener still exists
+                // 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();
+                     ++searchListenerIterator)
+                {
+                    if (searchListenerIterator->listener ==
+                        trackedListenersIterator->listener &&
+                        searchListenerIterator->mode ==
+                        trackedListenersIterator->mode)
+                    {
+                        listenerStillExists = true;
+                        break;
+                    }
+                }
+
+                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) {
+                    continue;
+                }
+
+                // Call waitable event watch listener
+                LogPedantic("Before tracker listener call...");
+                trackedListenersIterator->listener->OnWaitableHandleEvent(
+                    trackedWatchersIterator->first,
+                    trackedListenersIterator->mode);
+                LogPedantic("After tracker listener call...");
+            }
+
+            // Now call all those listeners who registered during listener calls
+            // FIXME: Implement! Notice, that scenario may be recursive!
+
+            LogPedantic("Waitable event listeners called");
+
+            // No more waitable events possible - consistency check
+            break;
+        }
+    }
+}
+
+void WaitableHandleWatchSupport::AddWaitableHandleWatch(
+    WaitableHandleListener* listener,
+    WaitableHandle waitableHandle,
+    WaitMode::Type mode)
+{
+    // Enter waitable event list critical section
+    std::lock_guard<std::recursive_mutex> 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();
+             listenersIterator != mapIterator->second.listeners.end();
+             ++listenersIterator)
+        {
+            // Must not insert same listener-mode pair
+            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));
+    }
+
+    // Update counters
+    switch (mode) {
+    case WaitMode::Read:
+        m_watchersMap[waitableHandle].readListenersCount++;
+        break;
+
+    case WaitMode::Write:
+        m_watchersMap[waitableHandle].writeListenersCount++;
+        break;
+
+    default:
+        Assert(0);
+    }
+
+    // Trigger waitable event invoker to commit changes
+    CommitInvoker();
+
+    LogPedantic("Waitable event watch added and invoker signaled");
+}
+
+void WaitableHandleWatchSupport::RemoveWaitableHandleWatch(
+    WaitableHandleListener *listener,
+    WaitableHandle waitableHandle,
+    WaitMode::Type mode)
+{
+    // Enter waitable event list critical section
+    std::lock_guard<std::recursive_mutex> lock(m_watchersMutex);
+
+    // Find proper list with listener
+    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();
+
+    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)
+        {
+            listIterator = listenersIterator;
+            break;
+        }
+    }
+
+    // Same pair listener-mode must exist
+    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;
+
+    case WaitMode::Write:
+        mapIterator->second.writeListenersCount--;
+        break;
+
+    default:
+        Assert(0);
+    }
+
+    // If list is empty, remove it too
+    if (mapIterator->second.listeners.empty()) {
+        m_watchersMap.erase(mapIterator);
+    }
+
+    // Trigger waitable event invoker to commit changes
+    CommitInvoker();
+
+    LogPedantic("Waitable event watch removed and invoker signaled");
+}
+
+void WaitableHandleWatchSupport::CommitInvoker()
+{
+    // Check calling context and execute invoker
+    if (Thread::GetCurrentThread() == GetInvokerThread()) {
+        LogPedantic("Calling direct invoker");
+
+        // Direct invoker call
+        HandleDirectInvoker();
+    } else {
+        LogPedantic("Calling indirect invoker");
+
+        // Indirect invoker call
+        m_watchersInvoker.Signal();
+
+        WaitableHandleList waitHandles;
+        waitHandles.push_back(m_watchersInvokerCommit.GetHandle());
+        WaitForMultipleHandles(waitHandles);
+
+        m_watchersInvokerCommit.Reset();
+    }
+}
+
+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) {
+        return Thread::GetCurrentThread();
+    } /*else {
+        return &MainSingleton::Instance();
+    }*/
+}
+} // namespace DPL
diff --git a/commons/modules/db/config.cmake b/commons/modules/db/config.cmake
new file mode 100644 (file)
index 0000000..40012ab
--- /dev/null
@@ -0,0 +1,46 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+#
+# @file        config.cmake
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+SET(DPL_DB_SOURCES
+    ${PROJECT_SOURCE_DIR}/modules/db/src/naive_synchronization_object.cpp
+    ${PROJECT_SOURCE_DIR}/modules/db/src/orm.cpp
+    ${PROJECT_SOURCE_DIR}/modules/db/src/sql_connection.cpp
+    ${PROJECT_SOURCE_DIR}/modules/db/src/thread_database_support.cpp
+    PARENT_SCOPE
+)
+
+
+SET(DPL_DB_HEADERS
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/naive_synchronization_object.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/orm_generator.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/orm.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/orm_interface.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/orm_macros.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/sql_connection.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/thread_database_support.h
+    PARENT_SCOPE
+)
+
+SET(DPL_DB_INCLUDE_DIR
+    ${PROJECT_SOURCE_DIR}/modules/db/include
+    ${PROJECT_SOURCE_DIR}/modules/core/include/
+    PARENT_SCOPE
+)
diff --git a/commons/modules/db/include/dpl/db/naive_synchronization_object.h b/commons/modules/db/include/dpl/db/naive_synchronization_object.h
new file mode 100644 (file)
index 0000000..2f63a0f
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        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
+ */
+#ifndef DPL_NAIVE_SYNCHRONIZATION_OBJECT_H
+#define DPL_NAIVE_SYNCHRONIZATION_OBJECT_H
+
+#include <dpl/db/sql_connection.h>
+
+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
+{
+  public:
+    // [SqlConnection::SynchronizationObject]
+    virtual void Synchronize();
+    virtual void NotifyAll();
+};
+} // namespace DB
+} // namespace DPL
+
+#endif // DPL_NAIVE_SYNCHRONIZATION_OBJECT_H
diff --git a/commons/modules/db/include/dpl/db/orm.h b/commons/modules/db/include/dpl/db/orm.h
new file mode 100644 (file)
index 0000000..0f36516
--- /dev/null
@@ -0,0 +1,1116 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        orm.h
+ * @author      Bartosz Janiak (b.janiak@samsung.com)
+ * @version     1.0
+ * @brief       DPL-ORM: Object-relational mapping for sqlite database, written on top of DPL.
+ */
+
+#include <cstdlib>
+#include <cstdio>
+#include <string>
+#include <typeinfo>
+#include <utility>
+#include <set>
+#include <memory>
+#include <boost/optional.hpp>
+
+#include <dpl/db/sql_connection.h>
+#include <dpl/db/orm_interface.h>
+#include <dpl/string.h>
+#include <dpl/type_list.h>
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+
+#ifndef DPL_ORM_H
+#define DPL_ORM_H
+
+namespace DPL {
+namespace DB {
+namespace ORM {
+
+//TODO move to type utils
+#define DPL_CHECK_TYPE_INSTANTIABILITY(type) \
+    { \
+        type _ignored_; \
+        (void)_ignored_; \
+    }
+
+#define DECLARE_COLUMN_TYPE_LIST() typedef DPL::TypeListDecl<
+#define SELECTED_COLUMN(table_name, column_name) table_name::column_name,
+#define DECLARE_COLUMN_TYPE_LIST_END(name) DPL::TypeListGuard>::Type name;
+
+typedef size_t ColumnIndex;
+typedef size_t ArgumentIndex;
+typedef boost::optional<DPL::String> OptionalString;
+typedef boost::optional<int> OptionalInteger;
+typedef DPL::DB::SqlConnection::DataCommand DataCommand;
+
+namespace RelationTypes {
+    extern const char Equal[];
+    extern const char LessThan[];
+    extern const char And[];
+    extern const char Or[];
+    extern const char Is[];
+    extern const char In[];
+    //TODO define more relation types
+}
+
+namespace DataCommandUtils {
+    //TODO move to DPL::DataCommand?
+    void BindArgument(DataCommand *command, ArgumentIndex index, int argument);
+    void BindArgument(DataCommand *command, ArgumentIndex index, const OptionalInteger& argument);
+    void BindArgument(DataCommand *command, ArgumentIndex index, const DPL::String& argument);
+    void BindArgument(DataCommand *command, ArgumentIndex index, const OptionalString& argument);
+}
+class __attribute__ ((visibility("hidden"))) Expression {
+public:
+    virtual ~Expression() {}
+    virtual std::string GetString() const = 0;
+    virtual ArgumentIndex BindTo(DataCommand *command, ArgumentIndex index) = 0;
+};
+
+typedef std::shared_ptr<Expression> ExpressionPtr;
+
+namespace OrderingUtils {
+
+template<typename CompoundType> inline std::string OrderByInternal()
+{
+    std::string order = OrderByInternal<typename CompoundType::Tail>();
+    if(!order.empty()) return CompoundType::Head::GetString() + ", " + order;
+    else return CompoundType::Head::GetString();
+}
+
+template<> inline std::string OrderByInternal<TypeListGuard>()
+{
+    return std::string();
+}
+
+}
+
+template<typename ColumnType>
+class __attribute__ ((visibility("hidden"))) OrderingExpression {
+protected:
+    static std::string GetSchemaAndName()
+    {
+        std::string statement;
+        statement += ColumnType::GetTableName();
+        statement += ".";
+        statement += ColumnType::GetColumnName();
+        statement += " ";
+        return statement;
+    }
+public:
+    virtual ~OrderingExpression() {}
+};
+
+template<const char* Operator, typename LeftExpression, typename RightExpression>
+class __attribute__ ((visibility("hidden"))) BinaryExpression : public Expression {
+protected:
+    LeftExpression  m_leftExpression;
+    RightExpression m_rightExpression;
+    bool            m_outerParenthesis;
+public:
+    BinaryExpression(const LeftExpression& leftExpression, const RightExpression& rightExpression, bool outerParenthesis = true) :
+        m_leftExpression(leftExpression),
+        m_rightExpression(rightExpression),
+        m_outerParenthesis(outerParenthesis)
+    {}
+
+    virtual std::string GetString() const
+    {
+        return  (m_outerParenthesis ? "( " : " " ) +
+                 m_leftExpression.GetString() + " " + Operator + " " + m_rightExpression.GetString() +
+                (m_outerParenthesis ? " )" : " " ) ;
+    }
+
+    virtual ArgumentIndex BindTo(DataCommand *command, ArgumentIndex index)
+    {
+        index = m_leftExpression.BindTo(command, index);
+        return  m_rightExpression.BindTo(command, index);
+    }
+
+    template<typename TableDefinition>
+    struct ValidForTable {
+        typedef std::pair<typename LeftExpression ::template ValidForTable<TableDefinition>::Yes ,
+                          typename RightExpression::template ValidForTable<TableDefinition>::Yes >
+                Yes;
+    };
+};
+
+template<typename LeftExpression, typename RightExpression>
+BinaryExpression<RelationTypes::And, LeftExpression, RightExpression>
+    And(const LeftExpression& leftExpression, const RightExpression& rightExpression)
+{
+    return BinaryExpression<RelationTypes::And, LeftExpression, RightExpression>
+            (leftExpression, rightExpression);
+}
+
+template<typename LeftExpression, typename RightExpression>
+BinaryExpression<RelationTypes::Or, LeftExpression, RightExpression>
+    Or(const LeftExpression& leftExpression, const RightExpression& rightExpression)
+{
+    return BinaryExpression<RelationTypes::Or, LeftExpression, RightExpression>
+            (leftExpression, rightExpression);
+}
+
+template<typename ArgumentType>
+class __attribute__ ((visibility("hidden"))) ExpressionWithArgument : public Expression {
+protected:
+    ArgumentType argument;
+
+public:
+    explicit ExpressionWithArgument(const ArgumentType& _argument) : argument(_argument) {}
+
+    virtual ArgumentIndex BindTo(DataCommand *command, ArgumentIndex index)
+    {
+        DataCommandUtils::BindArgument(command, index, argument);
+        return index + 1;
+    }
+};
+
+template<typename ColumnData, const char* Relation>
+class __attribute__ ((visibility("hidden"))) Compare : public ExpressionWithArgument<typename ColumnData::ColumnType> {
+public:
+    explicit Compare(typename ColumnData::ColumnType column) :
+        ExpressionWithArgument<typename ColumnData::ColumnType>(column)
+    {}
+
+    virtual std::string GetString() const
+    {
+        std::string statement;
+        statement += ColumnData::GetTableName();
+        statement += ".";
+        statement += ColumnData::GetColumnName();
+        statement += " ";
+        statement += Relation;
+        statement += " ?";
+        return statement;
+    }
+
+    template<typename TableDefinition>
+    struct ValidForTable {
+        typedef typename TableDefinition::ColumnList::template Contains<ColumnData> Yes;
+    };
+};
+#define ORM_DEFINE_COMPARE_EXPRESSION(name, relationType)                      \
+    template<typename ColumnData>                                              \
+    class __attribute__ ((visibility("hidden"))) name : public Compare<ColumnData, RelationTypes::relationType> {     \
+    public:                                                                    \
+        name(typename ColumnData::ColumnType column) :                         \
+            Compare<ColumnData, RelationTypes::relationType>(column)           \
+        {}                                                                     \
+    };
+
+ORM_DEFINE_COMPARE_EXPRESSION(Equals, Equal)
+ORM_DEFINE_COMPARE_EXPRESSION(Is, Is)
+
+#define ORM_DEFINE_ORDERING_EXPRESSION(name, value)                                     \
+    template<typename ColumnType>                                                       \
+    class __attribute__ ((visibility("hidden"))) name                                   \
+        : OrderingExpression<ColumnType> {                                              \
+    public:                                                                             \
+        static std::string GetString()                                                  \
+        {                                                                               \
+            std::string statement = OrderingExpression<ColumnType>::GetSchemaAndName(); \
+            statement += value;                                                         \
+            return statement;                                                           \
+        }                                                                               \
+    };
+
+ORM_DEFINE_ORDERING_EXPRESSION(OrderingAscending, "ASC")
+ORM_DEFINE_ORDERING_EXPRESSION(OrderingDescending, "DESC")
+
+template<typename ColumnData1, typename ColumnData2>
+class __attribute__ ((visibility("hidden"))) CompareBinaryColumn {
+private:
+    std::string m_relation;
+public:
+    CompareBinaryColumn(const char* Relation) :
+      m_relation(Relation)
+    {}
+
+    virtual ~CompareBinaryColumn() {}
+
+    virtual std::string GetString() const
+    {
+        std::string statement;
+        statement += ColumnData1::GetTableName();
+        statement += ".";
+        statement += ColumnData1::GetColumnName();
+        statement += " ";
+        statement += m_relation;
+        statement += " ";
+        statement += ColumnData2::GetTableName();
+        statement += ".";
+        statement += ColumnData2::GetColumnName();
+
+        return statement;
+    }
+};
+
+template<typename ColumnData1, typename ColumnData2>
+CompareBinaryColumn<ColumnData1, ColumnData2>
+    Equal()
+{
+    return CompareBinaryColumn<ColumnData1, ColumnData2>(RelationTypes::Equal);
+}
+
+template<typename ColumnData, const char* Relation>
+class __attribute__ ((visibility("hidden"))) NumerousArguments : public Expression {
+protected:
+    std::set<typename ColumnData::ColumnType> m_argumentList;
+public:
+    NumerousArguments(const std::set<typename ColumnData::ColumnType>& argumentList) : m_argumentList(argumentList) {}
+
+    virtual std::string GetString() const
+    {
+        std::string statement;
+        statement += ColumnData::GetColumnName();
+        statement += " ";
+        statement += Relation;
+        statement += " ( ";
+
+        int argumentCount = m_argumentList.size();
+        while(argumentCount)
+        {
+            statement += "?";
+            argumentCount--;
+            if (argumentCount)
+            {
+                statement += ", ";
+            }
+        }
+
+        statement += " )";
+
+        return statement;
+    }
+
+    virtual ArgumentIndex BindTo(DataCommand *command, ArgumentIndex index)
+    {
+        ArgumentIndex argumentIndex = index;
+        FOREACH(argumentIt, m_argumentList)
+        {
+            DataCommandUtils::BindArgument(command, argumentIndex, *argumentIt);
+            argumentIndex++;
+        }
+        return  argumentIndex + 1;
+    }
+
+    template<typename TableDefinition>
+    struct ValidForTable {
+        typedef typename TableDefinition::ColumnList::template Contains<ColumnData> Yes;
+    };
+};
+
+#define ORM_DEFINE_COMPARE_EXPRESSION_NUMEROUS_ARGUMENTS(name, relationType)                      \
+    template<typename ColumnData>                                              \
+    class __attribute__ ((visibility("hidden"))) name : public NumerousArguments<ColumnData, RelationTypes::relationType> {     \
+    public:                                                                    \
+        name(std::set<typename ColumnData::ColumnType> column) :                         \
+            NumerousArguments<ColumnData, RelationTypes::relationType>(column)           \
+        {}                                                                     \
+    };
+
+ORM_DEFINE_COMPARE_EXPRESSION_NUMEROUS_ARGUMENTS(In, In)
+
+template<typename ColumnType>
+ColumnType GetColumnFromCommand(ColumnIndex columnIndex, DataCommand *command);
+
+class __attribute__ ((visibility("hidden"))) CustomColumnBase {
+public:
+    CustomColumnBase() {}
+    virtual ~CustomColumnBase() {}
+};
+
+template<typename ColumnType>
+class __attribute__ ((visibility("hidden"))) CustomColumn : public CustomColumnBase {
+private:
+    ColumnType m_columnData;
+
+public:
+    CustomColumn() {}
+    CustomColumn(ColumnType data)
+    {
+        m_columnData = data;
+    }
+
+    void SetColumnData(ColumnType data)
+    {
+        m_columnData = data;
+    }
+
+    ColumnType GetColumnData() const
+    {
+        return m_columnData;
+    }
+};
+
+template<typename ColumnList>
+class __attribute__ ((visibility("hidden"))) CustomRowUtil {
+public:
+    static void MakeColumnList(std::vector<CustomColumnBase*>& columnList)
+    {
+        typedef CustomColumn<typename ColumnList::Head::ColumnType> Type;
+        Type* pColumn = new Type();
+        columnList.push_back(pColumn);
+        CustomRowUtil<typename ColumnList::Tail>::MakeColumnList(columnList);
+    }
+
+    static void CopyColumnList(const std::vector<CustomColumnBase*>& srcList, std::vector<CustomColumnBase*>& dstList)
+    {
+        CopyColumnList(srcList, dstList, 0);
+    }
+
+    static ColumnIndex GetColumnIndex(const std::string& columnName)
+    {
+        return GetColumnIndex(columnName, 0);
+    }
+
+private:
+    static void CopyColumnList(const std::vector<CustomColumnBase*>& srcList, std::vector<CustomColumnBase*>& dstList, ColumnIndex index)
+    {
+        typedef CustomColumn<typename ColumnList::Head::ColumnType> Type;
+        Type* pColumn = new Type(((Type*)(srcList.at(index)))->GetColumnData());
+        dstList.push_back(pColumn);
+        CustomRowUtil<typename ColumnList::Tail>::CopyColumnList(srcList, dstList, index + 1);
+    }
+
+    static ColumnIndex GetColumnIndex(const std::string& columnName, ColumnIndex index)
+    {
+        if (ColumnList::Head::GetColumnName() == columnName)
+            return index;
+
+        return CustomRowUtil<typename ColumnList::Tail>::GetColumnIndex(columnName, index + 1);
+    }
+
+template<typename Other>
+friend class CustomRowUtil;
+};
+
+template<>
+class __attribute__ ((visibility("hidden"))) CustomRowUtil<DPL::TypeListGuard> {
+public:
+    static void MakeColumnList(std::vector<CustomColumnBase*>&) {}
+private:
+    static void CopyColumnList(const std::vector<CustomColumnBase*>&, std::vector<CustomColumnBase*>&, ColumnIndex) {}
+    static ColumnIndex GetColumnIndex(const std::string&, ColumnIndex) { return -1; }
+
+template<typename Other>
+friend class CustomRowUtil;
+};
+
+template<typename ColumnList>
+class __attribute__ ((visibility("hidden"))) CustomRow {
+private:
+    std::vector<CustomColumnBase*> m_columns;
+
+public:
+    CustomRow()
+    {
+        CustomRowUtil<ColumnList>::MakeColumnList(m_columns);
+    }
+
+    CustomRow(const CustomRow& r)
+    {
+        CustomRowUtil<ColumnList>::CopyColumnList(r.m_columns, m_columns);
+    }
+
+    virtual ~CustomRow()
+    {
+        while (!m_columns.empty())
+        {
+            CustomColumnBase* pCustomColumn = m_columns.back();
+            m_columns.pop_back();
+            if (pCustomColumn)
+                delete pCustomColumn;
+        }
+    }
+
+    template<typename ColumnType>
+    void SetColumnData(ColumnIndex columnIndex, ColumnType data)
+    {
+        typedef CustomColumn<ColumnType> Type;
+        Assert(columnIndex < m_columns.size());
+        Type* pColumn = dynamic_cast<Type*>(m_columns.at(columnIndex));
+        Assert(pColumn);
+        pColumn->SetColumnData(data);
+    }
+
+    template<typename ColumnData>
+    typename ColumnData::ColumnType GetColumnData()
+    {
+        typedef CustomColumn<typename ColumnData::ColumnType> Type;
+        ColumnIndex index = CustomRowUtil<ColumnList>::GetColumnIndex(ColumnData::GetColumnName());
+        Assert(index < m_columns.size());
+        Type* pColumn = dynamic_cast<Type*>(m_columns.at(index));
+        Assert(pColumn);
+        return pColumn->GetColumnData();
+    }
+};
+
+template<typename CustomRow, typename ColumnType>
+void SetColumnData(CustomRow& row, ColumnType columnData, ColumnIndex columnIndex)
+{
+    row.SetColumnData<ColumnType>(columnIndex, columnData);
+}
+
+template<typename ColumnList, typename CustomRow>
+class  __attribute__ ((visibility("hidden"))) FillCustomRowUtil {
+public:
+    static void FillCustomRow(CustomRow& row, DataCommand* command)
+    {
+        FillCustomRow(row, 0, command);
+    }
+
+private:
+    static void FillCustomRow(CustomRow& row, ColumnIndex columnIndex, DataCommand* command)
+    {
+        typename ColumnList::Head::ColumnType columnData;
+        columnData = GetColumnFromCommand<typename ColumnList::Head::ColumnType>(columnIndex, command);
+        SetColumnData<CustomRow, typename ColumnList::Head::ColumnType>(row, columnData, columnIndex);
+        FillCustomRowUtil<typename ColumnList::Tail, CustomRow>::FillCustomRow(row, columnIndex + 1, command);
+    }
+
+template<typename Other, typename OtherRow>
+friend class FillCustomRowUtil;
+};
+
+template<typename CustomRow>
+class  __attribute__ ((visibility("hidden"))) FillCustomRowUtil<DPL::TypeListGuard, CustomRow> {
+private:
+    static void FillCustomRow(CustomRow&, ColumnIndex, DataCommand *)
+    { /* do nothing, we're past the last element of column list */ }
+
+template<typename Other, typename OtherRow>
+friend class FillCustomRowUtil;
+};
+
+template<typename ColumnList, typename Row>
+class  __attribute__ ((visibility("hidden"))) FillRowUtil {
+public:
+    static void FillRow(Row& row, DataCommand *command)
+    {
+        FillRow(row, 0, command);
+    }
+
+private:
+    static void FillRow(Row& row, ColumnIndex columnIndex, DataCommand *command)
+    {
+        typename ColumnList::Head::ColumnType rowField;
+        rowField = GetColumnFromCommand<typename ColumnList::Head::ColumnType>(columnIndex, command);
+        ColumnList::Head::SetRowField(row, rowField);
+        FillRowUtil<typename ColumnList::Tail, Row>::FillRow(row, columnIndex + 1, command);
+    }
+
+template<typename Other, typename OtherRow>
+friend class FillRowUtil;
+};
+
+template<typename Row>
+class  __attribute__ ((visibility("hidden"))) FillRowUtil<DPL::TypeListGuard, Row> {
+private:
+    static void FillRow(Row&, ColumnIndex, DataCommand *)
+    { /* do nothing, we're past the last element of column list */ }
+
+template<typename Other, typename OtherRow>
+friend class FillRowUtil;
+};
+
+template<typename ColumnList>
+class  __attribute__ ((visibility("hidden"))) JoinUtil {
+public:
+    static std::string GetColumnNames()
+    {
+        std::string result;
+        result = ColumnList::Head::GetTableName();
+        result += ".";
+        result += ColumnList::Head::GetColumnName();
+        if (ColumnList::Tail::Size > 0)
+            result += ", ";
+
+        return result += JoinUtil<typename ColumnList::Tail>::GetColumnNames();
+    }
+
+    static std::string GetJoinTableName(const std::string& tableName)
+    {
+        std::string joinTableName = ColumnList::Head::GetTableName();
+        if (tableName.find(joinTableName) == std::string::npos)
+            return joinTableName;
+
+        return JoinUtil<typename ColumnList::Tail>::GetJoinTableName(tableName);
+    }
+};
+
+template<>
+class  __attribute__ ((visibility("hidden"))) JoinUtil<DPL::TypeListGuard> {
+public:
+    static std::string GetColumnNames() { return ""; }
+    static std::string GetJoinTableName(std::string) { return ""; }
+};
+
+class Exception {
+public:
+    DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+    DECLARE_EXCEPTION_TYPE(Base, SelectReuseWithDifferentQuerySignature)
+    DECLARE_EXCEPTION_TYPE(Base, RowFieldNotInitialized)
+    DECLARE_EXCEPTION_TYPE(Base, EmptyUpdateStatement)
+};
+
+template<typename TableDefinition>
+class  __attribute__ ((visibility("hidden"))) Query
+{
+protected:
+    explicit Query(IOrmInterface* interface) :
+        m_interface(interface),
+        m_command(NULL)
+    {
+    }
+
+    virtual ~Query()
+    {
+        if (m_command == NULL)
+            return;
+
+        TableDefinition::FreeTableDataCommand(m_command, m_interface);
+    }
+
+    IOrmInterface* m_interface;
+    DataCommand *m_command;
+    std::string m_commandString;
+    ArgumentIndex m_bindArgumentIndex;
+};
+
+template<typename TableDefinition>
+class  __attribute__ ((visibility("hidden"))) QueryWithWhereClause : public Query<TableDefinition>
+{
+protected:
+    ExpressionPtr m_whereExpression;
+
+    void Prepare()
+    {
+        if ( !!m_whereExpression )
+        {
+            this->m_commandString += " WHERE ";
+            this->m_commandString += m_whereExpression->GetString();
+        }
+    }
+
+    void Bind()
+    {
+        if ( !!m_whereExpression )
+        {
+            this->m_bindArgumentIndex = m_whereExpression->BindTo(
+                this->m_command, this->m_bindArgumentIndex);
+        }
+    }
+
+public:
+    explicit QueryWithWhereClause(IOrmInterface* interface) :
+        Query<TableDefinition>(interface)
+    {
+    }
+
+    template<typename Expression>
+    void Where(const Expression& expression)
+    {
+        DPL_CHECK_TYPE_INSTANTIABILITY(typename Expression::template ValidForTable<TableDefinition>::Yes);
+        if ( !!m_whereExpression && ( typeid(Expression) != typeid(*m_whereExpression) ) )
+        {
+            std::ostringstream str;
+            str << "Current ORM implementation doesn't allow to reuse Select"
+                    " instance with different query signature (particularly "
+                    "WHERE on different column).\n";
+            str << "Query: ";
+            str << this->m_commandString;
+            ThrowMsg(Exception::SelectReuseWithDifferentQuerySignature,
+                str.str());
+        }
+        //TODO maybe don't make a copy here but just generate the string part of the query.
+        m_whereExpression.reset(new Expression(expression));
+    }
+
+};
+
+template<typename TableDefinition>
+class  __attribute__ ((visibility("hidden"))) Delete : public QueryWithWhereClause<TableDefinition>
+{
+protected:
+    void Prepare()
+    {
+        if ( !this->m_command)
+        {
+            this->m_commandString  = "DELETE FROM ";
+            this->m_commandString += TableDefinition::GetName();
+
+            QueryWithWhereClause<TableDefinition>::Prepare();
+
+            this->m_command = TableDefinition::AllocTableDataCommand(
+                    this->m_commandString.c_str(),
+                    Query<TableDefinition>::m_interface);
+            LogPedantic("Prepared SQL command " << this->m_commandString);
+        }
+    }
+
+    void Bind()
+    {
+        this->m_bindArgumentIndex = 1;
+        QueryWithWhereClause<TableDefinition>::Bind();
+    }
+
+public:
+    explicit Delete(IOrmInterface *interface = NULL) :
+        QueryWithWhereClause<TableDefinition>(interface)
+    {
+    }
+
+    void Execute()
+    {
+        Prepare();
+        Bind();
+        this->m_command->Step();
+        this->m_command->Reset();
+    }
+};
+
+namespace {
+class BindVisitor {
+private:
+    DataCommand *m_command;
+public:
+    ArgumentIndex m_bindArgumentIndex;
+
+    BindVisitor(DataCommand *command) :
+        m_command(command),
+        m_bindArgumentIndex(1)
+    {}
+
+    template<typename ColumnType>
+    void Visit(const char*, const ColumnType& value, bool isSet)
+    {
+        if ( isSet )
+        {
+            DataCommandUtils::BindArgument(m_command, m_bindArgumentIndex, value);
+            m_bindArgumentIndex++;
+        }
+    }
+};
+} //anonymous namespace
+template<typename TableDefinition>
+class __attribute__ ((visibility("hidden"))) Insert : public Query<TableDefinition>
+{
+public:
+    typedef typename TableDefinition::Row Row;
+    typedef DPL::DB::SqlConnection::RowID RowID;
+
+protected:
+    boost::optional<std::string> m_orClause;
+    Row m_row;
+
+    class PrepareVisitor {
+    public:
+        std::string m_columnNames;
+        std::string m_values;
+
+        template<typename ColumnType>
+        void Visit(const char* name, const ColumnType&, bool isSet)
+        {
+            if ( isSet )
+            {
+                if ( !m_columnNames.empty() )
+                {
+                    m_columnNames += ", ";
+                    m_values += ", ";
+                }
+                m_columnNames += name;
+                m_values += "?";
+            }
+        }
+    };
+
+    void Prepare()
+    {
+        if ( !this->m_command )
+        {
+            this->m_commandString = "INSERT ";
+            if ( !!m_orClause )
+            {
+                this->m_commandString += " OR " + *m_orClause + " ";
+            }
+            this->m_commandString += "INTO ";
+            this->m_commandString += TableDefinition::GetName();
+
+            PrepareVisitor visitor;
+            m_row.VisitColumns(visitor);
+
+            this->m_commandString += " ( " + visitor.m_columnNames + " ) ";
+            this->m_commandString += "VALUES ( " + visitor.m_values + " )";
+
+            LogPedantic("Prepared SQL command " << this->m_commandString);
+            this->m_command = TableDefinition::AllocTableDataCommand(
+                this->m_commandString.c_str(),
+                Query<TableDefinition>::m_interface);
+        }
+    }
+
+    void Bind()
+    {
+        BindVisitor visitor(this->m_command);
+        m_row.VisitColumns(visitor);
+    }
+
+public:
+    explicit Insert(
+            IOrmInterface* interface = NULL,
+            const boost::optional<std::string>& orClause = boost::optional<std::string>()) :
+        Query<TableDefinition>(interface),
+        m_orClause(orClause)
+    {
+    }
+
+    void Values(const Row& row)
+    {
+        if ( this->m_command )
+        {
+            if ( !row.IsSignatureMatching(m_row) )
+            {
+                ThrowMsg(Exception::SelectReuseWithDifferentQuerySignature,
+                    "Current ORM implementation doesn't allow to reuse Insert instance "
+                    "with different query signature.");
+            }
+        }
+        m_row = row;
+    }
+
+    RowID Execute()
+    {
+        Prepare();
+        Bind();
+        this->m_command->Step();
+
+        RowID result = TableDefinition::GetLastInsertRowID(
+            Query<TableDefinition>::m_interface);
+
+        this->m_command->Reset();
+        return result;
+    }
+};
+
+template<typename TableDefinition>
+class __attribute__ ((visibility("hidden"))) Select : public QueryWithWhereClause<TableDefinition>
+{
+public:
+    typedef typename TableDefinition::ColumnList       ColumnList;
+    typedef typename TableDefinition::Row              Row;
+
+    typedef std::list<Row>                             RowList;
+protected:
+    boost::optional<std::string> m_orderBy;
+    std::string m_JoinClause;
+    bool                       m_distinctResults;
+
+    void Prepare(const char* selectColumnName)
+    {
+        if ( !this->m_command )
+        {
+            this->m_commandString  = "SELECT ";
+            if (m_distinctResults)
+                this->m_commandString += "DISTINCT ";
+            this->m_commandString += selectColumnName;
+            this->m_commandString += " FROM ";
+            this->m_commandString += TableDefinition::GetName();
+
+            this->m_commandString += m_JoinClause;
+
+            QueryWithWhereClause<TableDefinition>::Prepare();
+
+            if ( !!m_orderBy )
+            {
+                this->m_commandString += " ORDER BY " + *m_orderBy;
+            }
+
+            this->m_command = TableDefinition::AllocTableDataCommand(
+                this->m_commandString.c_str(),
+                Query<TableDefinition>::m_interface);
+
+            LogPedantic("Prepared SQL command " << this->m_commandString);
+        }
+    }
+
+    void Bind()
+    {
+        this->m_bindArgumentIndex = 1;
+        QueryWithWhereClause<TableDefinition>::Bind();
+    }
+
+    template<typename ColumnType>
+    ColumnType GetColumn(ColumnIndex columnIndex)
+    {
+        return GetColumnFromCommand<ColumnType>(columnIndex, this->m_command);
+    }
+
+    Row GetRow()
+    {
+        Row row;
+        FillRowUtil<ColumnList, Row>::FillRow(row, this->m_command);
+        return row;
+    }
+
+    template<typename ColumnList, typename CustomRow>
+    CustomRow GetCustomRow()
+    {
+        CustomRow row;
+        FillCustomRowUtil<ColumnList, CustomRow>::FillCustomRow(row, this->m_command);
+        return row;
+    }
+
+public:
+
+    explicit Select(IOrmInterface *interface = NULL) :
+        QueryWithWhereClause<TableDefinition>(interface),
+        m_distinctResults(false)
+    {
+    }
+
+    void Distinct()
+    {
+        m_distinctResults = true;
+    }
+
+    template<typename CompoundType>
+    void OrderBy(const CompoundType&)
+    {
+        m_orderBy = OrderingUtils::OrderByInternal<typename CompoundType::Type>();
+    }
+
+    void OrderBy(const std::string & orderBy) //backward compatibility
+    {
+        m_orderBy = orderBy;
+    }
+
+    void OrderBy(const char * orderBy) //backward compatibility
+    {
+        m_orderBy = std::string(orderBy);
+    }
+
+    template<typename ColumnList, typename Expression>
+    void Join(const Expression& expression) {
+        std::string usedTableNames = TableDefinition::GetName();
+        if (!m_JoinClause.empty())
+            usedTableNames += m_JoinClause;
+
+        this->m_JoinClause += " JOIN ";
+        this->m_JoinClause += JoinUtil<ColumnList>::GetJoinTableName(usedTableNames);
+        this->m_JoinClause += " ON ";
+        this->m_JoinClause += expression.GetString();
+    }
+
+    template<typename ColumnData>
+    typename ColumnData::ColumnType GetSingleValue()
+    {
+        Prepare(ColumnData::GetColumnName());
+        Bind();
+        this->m_command->Step();
+
+        typename ColumnData::ColumnType result =
+            GetColumn<typename ColumnData::ColumnType>(0);
+
+        this->m_command->Reset();
+        return result;
+    }
+
+    //TODO return range - pair of custom iterators
+    template<typename ColumnData>
+    std::list<typename ColumnData::ColumnType> GetValueList()
+    {
+        Prepare(ColumnData::GetColumnName());
+        Bind();
+
+        std::list<typename ColumnData::ColumnType> resultList;
+
+        while (this->m_command->Step())
+            resultList.push_back(GetColumn<typename ColumnData::ColumnType>(0));
+
+        this->m_command->Reset();
+        return resultList;
+    }
+
+    Row GetSingleRow()
+    {
+        Prepare("*");
+        Bind();
+        this->m_command->Step();
+
+        Row result = GetRow();
+
+        this->m_command->Reset();
+        return result;
+    }
+
+    //TODO return range - pair of custom iterators
+    RowList GetRowList()
+    {
+        Prepare("*");
+        Bind();
+
+        RowList resultList;
+
+        while (this->m_command->Step())
+            resultList.push_back(GetRow());
+
+        this->m_command->Reset();
+        return resultList;
+    }
+
+    template<typename ColumnList, typename CustomRow>
+    CustomRow GetCustomSingleRow()
+    {
+        Prepare(JoinUtil<ColumnList>::GetColumnNames().c_str());
+        Bind();
+        this->m_command->Step();
+
+        CustomRow result = GetCustomRow<ColumnList, CustomRow>();
+
+        this->m_command->Reset();
+        return result;
+    }
+
+    template<typename ColumnList, typename CustomRow>
+    std::list<CustomRow> GetCustomRowList()
+    {
+        Prepare(JoinUtil<ColumnList>::GetColumnNames().c_str());
+        Bind();
+
+        std::list<CustomRow> resultList;
+
+        while (this->m_command->Step())
+            resultList.push_back(GetCustomRow<ColumnList, CustomRow>());
+
+        this->m_command->Reset();
+        return resultList;
+    }
+};
+
+template<typename TableDefinition>
+class __attribute__ ((visibility("hidden"))) Update : public QueryWithWhereClause<TableDefinition> {
+public:
+    typedef typename TableDefinition::Row Row;
+
+protected:
+    boost::optional<std::string> m_orClause;
+    Row m_row;
+
+    class PrepareVisitor {
+    public:
+        std::string m_setExpressions;
+
+        template<typename ColumnType>
+        void Visit(const char* name, const ColumnType&, bool isSet)
+        {
+            if ( isSet )
+            {
+                if ( !m_setExpressions.empty() )
+                {
+                    m_setExpressions += ", ";
+                }
+                m_setExpressions += name;
+                m_setExpressions += " = ";
+                m_setExpressions += "?";
+            }
+        }
+    };
+
+    void Prepare()
+    {
+        if ( !this->m_command )
+        {
+            this->m_commandString = "UPDATE ";
+            if ( !!m_orClause )
+            {
+                this->m_commandString += " OR " + *m_orClause + " ";
+            }
+            this->m_commandString += TableDefinition::GetName();
+            this->m_commandString += " SET ";
+
+            // got through row columns and values
+            PrepareVisitor visitor;
+            m_row.VisitColumns(visitor);
+
+            if(visitor.m_setExpressions.empty())
+            {
+                ThrowMsg(Exception::EmptyUpdateStatement, "No SET expressions in update statement");
+            }
+
+            this->m_commandString += visitor.m_setExpressions;
+
+            // where
+            QueryWithWhereClause<TableDefinition>::Prepare();
+
+            this->m_command = TableDefinition::AllocTableDataCommand(
+                    this->m_commandString.c_str(),
+                    Query<TableDefinition>::m_interface);
+            LogPedantic("Prepared SQL command " << this->m_commandString);
+        }
+    }
+
+    void Bind()
+    {
+        BindVisitor visitor(this->m_command);
+        m_row.VisitColumns(visitor);
+
+        this->m_bindArgumentIndex = visitor.m_bindArgumentIndex;
+        QueryWithWhereClause<TableDefinition>::Bind();
+    }
+
+
+public:
+    explicit Update(IOrmInterface *interface = NULL,
+                    const boost::optional<std::string>& orClause = boost::optional<std::string>()) :
+        QueryWithWhereClause<TableDefinition>(interface),
+        m_orClause(orClause)
+    {
+    }
+
+    void Values(const Row& row)
+    {
+        if ( this->m_command )
+        {
+            if ( !row.IsSignatureMatching(m_row) )
+            {
+                ThrowMsg(Exception::SelectReuseWithDifferentQuerySignature,
+                    "Current ORM implementation doesn't allow to reuse Update instance "
+                    "with different query signature.");
+            }
+        }
+        m_row = row;
+    }
+
+    void Execute()
+    {
+        Prepare();
+        Bind();
+        this->m_command->Step();
+        this->m_command->Reset();
+    }
+};
+
+} //namespace ORM
+} //namespace DB
+} //namespace DPL
+
+#endif // DPL_ORM_H
diff --git a/commons/modules/db/include/dpl/db/orm_generator.h b/commons/modules/db/include/dpl/db/orm_generator.h
new file mode 100644 (file)
index 0000000..ca62410
--- /dev/null
@@ -0,0 +1,382 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        orm_generator.h
+ * @author      Bartosz Janiak (b.janiak@samsung.com)
+ * @version     1.0
+ * @brief       Macro definitions for generating the DPL-ORM table definitions from database definitions.
+ */
+
+#ifndef ORM_GENERATOR_DATABASE_NAME
+#error You need to define database name in ORM_GENERATOR_DATABASE_NAME define before you include orm_generator.h file
+#endif
+
+#include <dpl/db/orm_interface.h>
+
+#define ORM_GENERATOR_DATABASE_NAME_LOCAL <ORM_GENERATOR_DATABASE_NAME>
+
+#ifdef DPL_ORM_GENERATOR_H
+#warning orm_generator.h is included multiply times. Make sure it has different ORM_GENERATOR_DATABASE_NAME set.
+#endif
+
+#define DPL_ORM_GENERATOR_H
+
+
+#include <boost/optional.hpp>
+#include <dpl/string.h>
+#include <dpl/type_list.h>
+#include <dpl/db/sql_connection.h>
+#include <dpl/db/orm.h>
+#include <dpl/assert.h>
+#include <string>
+
+/*
+
+This is true only when exactly one db is available.
+
+#if (defined DECLARE_COLUMN) || (defined INT) || (defined TINYINT) ||               \
+    (defined INTEGER) || (defined BIGINT) || defined(VARCHAR) || defined(TEXT) ||   \
+    (defined SQL) || (defined TABLE_CONSTRAINTS) || (defined OPTIONAL) ||           \
+    (defined DATABASE_START) || (defined DATABASE_END) || (defined CREATE_TABLE) || \
+    (defined COLUMN) || (defined COLUMN_NOT_NULL) || (defined CREATE_TABLE_END)
+
+#error  This file temporarily defines many macros with generic names. To avoid name clash please include \
+        this file as early as possible. If this is not possible please report this problem to DPL developers.
+
+#endif
+*/
+
+namespace DPL {
+namespace DB {
+namespace ORM {
+
+// Global macros
+
+#define STRINGIFY(s) _str(s)
+#define _str(s) #s
+#define DECLARE_COLUMN(FIELD, TYPE) \
+    struct FIELD { \
+        typedef TYPE ColumnType; \
+        static const char* GetTableName() { return GetName(); } \
+        static const char* GetColumnName() { return STRINGIFY(FIELD); } \
+        static void SetRowField(Row& row, const TYPE& _value) { row.Set_##FIELD(_value);} \
+    };
+
+#define INT         int
+#define TINYINT     int
+#define INTEGER     int  //TODO: should be long long?
+#define BIGINT      int  //TODO: should be long long?
+#define VARCHAR(x)  DPL::String
+#define TEXT        DPL::String
+
+#define SQL(...)
+#define TABLE_CONSTRAINTS(...)
+#define OPTIONAL(type) boost::optional< type >
+#define DATABASE_START(db_name)                                 \
+    namespace db_name                                           \
+    {                                                           \
+        class ScopedTransaction                                 \
+        {                                                       \
+            bool m_commited;                                    \
+            IOrmInterface *m_interface;                         \
+                                                                \
+        public:                                                 \
+            ScopedTransaction(IOrmInterface *interface) :       \
+                m_commited(false),                              \
+                m_interface(interface)                          \
+            {                                                   \
+                Assert(interface != NULL);                      \
+                m_interface->TransactionBegin();                \
+            }                                                   \
+                                                                \
+            ~ScopedTransaction()                                \
+            {                                                   \
+                if (!m_commited)                                \
+                    m_interface->TransactionRollback();         \
+            }                                                   \
+                                                                \
+            void Commit()                                       \
+            {                                                   \
+                m_interface->TransactionCommit();               \
+                m_commited = true;                              \
+            }                                                   \
+        };
+
+#define DATABASE_END() }
+
+// RowBase ostream operator<< declaration
+
+#define CREATE_TABLE(name) \
+    namespace name {                                                            \
+        class RowBase;                                                          \
+        inline std::ostream& operator<<(std::ostream& ostr, const RowBase& row); \
+    }
+#define COLUMN_NOT_NULL(name, type, ...)
+#define COLUMN(name, type, ...)
+#define CREATE_TABLE_END()
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+#undef DATABASE_START
+#define DATABASE_START(db_name) namespace db_name {
+
+// RowBase class
+
+#define CREATE_TABLE(name) namespace name { class RowBase {                 \
+   public: friend std::ostream& operator<<(std::ostream&, const RowBase&);
+#define COLUMN_NOT_NULL(name, type, ...)                                \
+        protected: type name; bool m_##name##_set;                          \
+        public:  void Set_##name(const type& _value) {                       \
+                     m_##name##_set = true;                                 \
+                     this->name = _value;                                     \
+        }                                                                   \
+        public:  type Get_##name() const {                                  \
+                     if ( !m_##name##_set ) {                               \
+                        ThrowMsg(Exception::RowFieldNotInitialized,         \
+                        "You tried to read a row field that hasn't been set yet."); \
+                     }                                                      \
+                     return name;                                           \
+        }
+
+#define COLUMN(name, type, ...)                                         \
+        protected: OPTIONAL(type) name; bool m_##name##_set;                \
+        public:  void Set_##name(const OPTIONAL(type)& _value) {             \
+                     m_##name##_set = true;                                 \
+                     this->name = _value;                                     \
+        }                                                                   \
+        public:  OPTIONAL(type) Get_##name() const {                        \
+                     if ( !m_##name##_set ) {                               \
+                        ThrowMsg(Exception::RowFieldNotInitialized,         \
+                        "You tried to read a row field that hasn't been set yet."); \
+                     }                                                      \
+                     return name;                                           \
+        }
+#define CREATE_TABLE_END() }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// RowBase ostream operator<<
+
+#define CREATE_TABLE(name) std::ostream& name::operator<<(std::ostream& ostr, const RowBase& row) { using ::operator<< ; ostr << STRINGIFY(name) << " (";
+#define COLUMN_NOT_NULL(name, type, ...) ostr << " '" << row.name << "'" ;
+#define COLUMN(name, type, ...)          ostr << " '" << row.name << "'" ;
+#define CREATE_TABLE_END() ostr << " )" ; return ostr; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// RowBase2 class (== RowBase + operator==)
+
+#define CREATE_TABLE(name) namespace name { class RowBase2 : public RowBase { \
+    public: bool operator==(const RowBase2& row) const { return true
+#define COLUMN_NOT_NULL(name, type, ...) && (this->name == row.name)
+#define COLUMN(name, type, ...)          && (this->name == row.name)
+#define CREATE_TABLE_END() ; } }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// RowBase3 class (== RowBase2 + operator<)
+
+#define CREATE_TABLE(name) namespace name { class RowBase3 : public RowBase2 { \
+    public: bool operator<(const RowBase3& row) const {
+#define COLUMN_NOT_NULL(name, type, ...) if (this->name < row.name) { return true; } if (this->name > row.name) { return false; }
+#define COLUMN(name, type, ...)          if (this->name < row.name) { return true; } if (this->name > row.name) { return false; }
+#define CREATE_TABLE_END() return false; } }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// RowBase4 class (== RowBase3 + IsSignatureMatching )
+
+#define CREATE_TABLE(name) namespace name { class RowBase4 : public RowBase3 { \
+    public: bool IsSignatureMatching(const RowBase4& row) const { return true
+#define COLUMN_NOT_NULL(name, type, ...) && (this->m_##name##_set == row.m_##name##_set)
+#define COLUMN(name, type, ...)          && (this->m_##name##_set == row.m_##name##_set)
+#define CREATE_TABLE_END() ; } }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// RowBase5 class (== RowBase4 + default constructor)
+
+#define CREATE_TABLE(name) namespace name { class RowBase5 : public RowBase4 { \
+    public: RowBase5() {
+#define COLUMN_NOT_NULL(name, type, ...) m_##name##_set = false;
+#define COLUMN(name, type, ...)          m_##name##_set = false;
+#define CREATE_TABLE_END() } }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// Row class (== RowBase5 + ForEachColumn )
+
+#define CREATE_TABLE(name) namespace name { class Row : public RowBase5 { \
+    public: template<typename Visitor>                                    \
+    void VisitColumns(Visitor& visitor) const {
+#define COLUMN_NOT_NULL(name, type, ...) visitor.Visit(STRINGIFY(name), this->name, this->m_##name##_set);
+#define COLUMN(name, type, ...)          visitor.Visit(STRINGIFY(name), this->name, this->m_##name##_set);
+#define CREATE_TABLE_END() } }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// Field structure declarations
+
+#define CREATE_TABLE(name) namespace name { \
+    static const char* GetName() { return STRINGIFY(name); }
+#define COLUMN_NOT_NULL(name, type, ...) DECLARE_COLUMN(name, type)
+#define COLUMN(name, type, ...) DECLARE_COLUMN(name, OPTIONAL(type))
+#define CREATE_TABLE_END() }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// ColumnList typedef
+
+#define CREATE_TABLE(name) namespace name { typedef DPL::TypeListDecl<
+#define COLUMN_NOT_NULL(name, type, ...) name,
+#define COLUMN(name, type, ...) name,
+#define CREATE_TABLE_END() DPL::TypeListGuard>::Type ColumnList; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// TableDefinition struct
+
+#define CREATE_TABLE(table_name)                                            \
+    namespace table_name {                                                  \
+        struct TableDefinition {                                            \
+            typedef table_name::ColumnList ColumnList;                      \
+            typedef table_name::Row Row;                                    \
+            static const char* GetName() { return STRINGIFY(table_name); }  \
+            static DPL::DB::SqlConnection::DataCommand *AllocTableDataCommand( \
+                const std::string &statement,                               \
+                IOrmInterface *interface)                                   \
+            {                                                               \
+                Assert(interface != NULL);                                  \
+                return interface->AllocDataCommand(statement);              \
+            }                                                               \
+            static void FreeTableDataCommand(                               \
+                DPL::DB::SqlConnection::DataCommand *command,               \
+                IOrmInterface *interface)                                   \
+            {                                                               \
+                Assert(interface != NULL);                                  \
+                interface->FreeDataCommand(command);                        \
+            }                                                               \
+            static DPL::DB::SqlConnection::RowID GetLastInsertRowID(        \
+                IOrmInterface *interface)                                   \
+            {                                                               \
+                Assert(interface != NULL);                                  \
+                return interface->GetLastInsertRowID();                     \
+            }                                                               \
+        };                                                                  \
+    }
+
+#define COLUMN_NOT_NULL(name, type, ...)
+#define COLUMN(name, type, ...)
+#define CREATE_TABLE_END()
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// Query typedefs
+
+#define CREATE_TABLE(name) \
+    namespace name { \
+        typedef Select<TableDefinition> Select; \
+        typedef Insert<TableDefinition> Insert; \
+        typedef Delete<TableDefinition> Delete; \
+        typedef Update<TableDefinition> Update; \
+    }
+#define COLUMN_NOT_NULL(name, type, ...)
+#define COLUMN(name, type, ...)
+#define CREATE_TABLE_END()
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+
+// Global undefs
+#undef INT
+#undef TINYINT
+#undef INTEGER
+#undef BIGINT
+#undef VARCHAR
+#undef TEXT
+
+#undef SQL
+#undef TABLE_CONSTRAINTS
+#undef OPTIONAL
+#undef DATABASE_START
+#undef DATABASE_END
+
+} //namespace ORM
+} //namespace DB
+} //namespace DPL
+
+#undef ORM_GENERATOR_DATABASE_NAME
+#undef ORM_GENERATOR_DATABASE_NAME_LOCAL
diff --git a/commons/modules/db/include/dpl/db/orm_interface.h b/commons/modules/db/include/dpl/db/orm_interface.h
new file mode 100644 (file)
index 0000000..62ec073
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    orm_interface.h
+ * @author  Lukasz Marek (l.marek@samsung.com)
+ * @version 1.0
+ */
+
+#include <string>
+#include <dpl/db/sql_connection.h>
+
+#ifndef DPL_ORM_INTERFACE_H
+#define DPL_ORM_INTERFACE_H
+
+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 void TransactionBegin() = 0;
+    virtual void TransactionCommit() = 0;
+    virtual void TransactionRollback() = 0;
+    virtual DPL::DB::SqlConnection::RowID GetLastInsertRowID() = 0;
+};
+}
+}
+}
+
+#endif
diff --git a/commons/modules/db/include/dpl/db/orm_macros.h b/commons/modules/db/include/dpl/db/orm_macros.h
new file mode 100644 (file)
index 0000000..a038523
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        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.
+ */
+
+//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 COLUMN_NOT_NULL(name, type, ...) name type __VA_ARGS__ not null,
+#define SQL(...) __VA_ARGS__
+#define TABLE_CONSTRAINTS(...) __VA_ARGS__,
+#define CREATE_TABLE_END() CHECK(1) );
+#define DATABASE_START(db_name)
+#define DATABASE_END()
+
diff --git a/commons/modules/db/include/dpl/db/sql_connection.h b/commons/modules/db/include/dpl/db/sql_connection.h
new file mode 100644 (file)
index 0000000..18a5d3f
--- /dev/null
@@ -0,0 +1,513 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        sql_connection.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of SQL connection
+ */
+#ifndef DPL_SQL_CONNECTION_H
+#define DPL_SQL_CONNECTION_H
+
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <dpl/availability.h>
+#include <memory>
+#include <boost/optional.hpp>
+#include <dpl/string.h>
+#include <dpl/log/log.h>
+#include <sqlite3.h>
+#include <string>
+#include <dpl/assert.h>
+#include <memory>
+#include <stdint.h>
+
+namespace DPL {
+namespace DB {
+/**
+ * SQL connection class
+ */
+class SqlConnection
+{
+  public:
+    /**
+     * SQL Exception classes
+     */
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SyntaxError)
+        DECLARE_EXCEPTION_TYPE(Base, ConnectionBroken)
+        DECLARE_EXCEPTION_TYPE(Base, InternalError)
+        DECLARE_EXCEPTION_TYPE(Base, InvalidColumn)
+    };
+
+    typedef int ColumnIndex;
+    typedef int ArgumentIndex;
+
+    /*
+     * SQL processed data command
+     */
+    class DataCommand :
+        private Noncopyable
+    {
+      private:
+        SqlConnection *m_masterConnection;
+        sqlite3_stmt *m_stmt;
+
+        void CheckBindResult(int result);
+        void CheckColumnIndex(SqlConnection::ColumnIndex column);
+
+        DataCommand(SqlConnection *connection, const char *buffer);
+
+        friend class SqlConnection;
+
+      public:
+        virtual ~DataCommand();
+
+        /**
+         * Bind null to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         */
+        void BindNull(ArgumentIndex position);
+
+        /**
+         * Bind int to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInteger(ArgumentIndex position, int value);
+
+        /**
+         * Bind int8_t to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt8(ArgumentIndex position, int8_t value);
+
+        /**
+         * Bind int16 to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt16(ArgumentIndex position, int16_t value);
+
+        /**
+         * Bind int32 to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt32(ArgumentIndex position, int32_t value);
+
+        /**
+         * Bind int64 to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt64(ArgumentIndex position, int64_t value);
+
+        /**
+         * Bind float to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindFloat(ArgumentIndex position, float value);
+
+        /**
+         * Bind double to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindDouble(ArgumentIndex position, double value);
+
+        /**
+         * Bind string to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindString(ArgumentIndex position, const char *value);
+
+        /**
+         * Bind string to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindString(ArgumentIndex position, const String& value);
+
+        /**
+         * Bind optional int to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInteger(ArgumentIndex position, const boost::optional<int> &value);
+
+        /**
+         * Bind optional int8 to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt8(ArgumentIndex position, const boost::optional<int8_t> &value);
+
+        /**
+         * Bind optional int16 to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt16(ArgumentIndex position, const boost::optional<int16_t> &value);
+
+        /**
+         * Bind optional int32 to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt32(ArgumentIndex position, const boost::optional<int32_t> &value);
+
+        /**
+         * Bind optional int64 to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt64(ArgumentIndex position, const boost::optional<int64_t> &value);
+
+        /**
+         * Bind optional float to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindFloat(ArgumentIndex position, const boost::optional<float> &value);
+
+        /**
+         * Bind optional double to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindDouble(ArgumentIndex position, const boost::optional<double> &value);
+
+        /**
+         * Bind optional string to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindString(ArgumentIndex position, const boost::optional<String> &value);
+
+        /**
+         * Execute the prepared statement and/or move
+         * to the next row of the result
+         *
+         * @return True when there was a row returned
+         */
+        bool Step();
+
+        /**
+         * Reset prepared statement's arguments
+         * All parameters will become null
+         */
+        void Reset();
+
+        /**
+         * Checks whether column value is null
+         *
+         * @throw Exception::InvalidColumn
+         */
+        bool IsColumnNull(ColumnIndex column);
+
+        /**
+         * Get integer value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        int GetColumnInteger(ColumnIndex column);
+
+        /**
+         * Get int8 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        int8_t GetColumnInt8(ColumnIndex column);
+
+        /**
+         * Get int16 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        int16_t GetColumnInt16(ColumnIndex column);
+        /**
+         * Get int32 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        int32_t GetColumnInt32(ColumnIndex column);
+
+        /**
+         * Get int64 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        int64_t GetColumnInt64(ColumnIndex column);
+
+        /**
+         * Get float value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        float GetColumnFloat(ColumnIndex column);
+
+        /**
+         * Get double value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        double GetColumnDouble(ColumnIndex column);
+
+        /**
+         * Get string value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        std::string GetColumnString(ColumnIndex column);
+
+        /**
+         * Get optional integer value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<int> GetColumnOptionalInteger(ColumnIndex column);
+
+        /**
+         * Get optional int8 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<int8_t> GetColumnOptionalInt8(ColumnIndex column);
+
+        /**
+         * Get optional int16value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<int16_t> GetColumnOptionalInt16(ColumnIndex column);
+
+        /**
+         * Get optional int32 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<int32_t> GetColumnOptionalInt32(ColumnIndex column);
+
+        /**
+         * Get optional int64 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<int64_t> GetColumnOptionalInt64(ColumnIndex column);
+
+        /**
+         * Get optional float value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<float> GetColumnOptionalFloat(ColumnIndex column);
+
+        /**
+         * Get optional double value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<double> GetColumnOptionalDouble(ColumnIndex column);
+
+        /**
+         * Get optional string value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<String> GetColumnOptionalString(ColumnIndex column);
+    };
+
+    // Move on copy semantics
+    typedef std::auto_ptr<DataCommand> DataCommandAutoPtr;
+
+    // Open flags
+    class Flag
+    {
+      public:
+        enum Type
+        {
+            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
+             *      that need that switched do CRW
+             */
+            RW = SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE |
+                SQLITE_OPEN_CREATE,
+            CRW = RW | SQLITE_OPEN_CREATE
+        };
+    };
+
+    // RowID
+    typedef sqlite3_int64 RowID;
+
+    /**
+     * Synchronization object used to synchronize SQL connection
+     * to the same database across different threads and processes
+     */
+    class SynchronizationObject
+    {
+      public:
+        virtual ~SynchronizationObject() {}
+
+        /**
+         * Synchronizes SQL connection for multiple clients.
+         */
+        virtual void Synchronize() = 0;
+
+        /**
+         * Notify all waiting clients that the connection is no longer locked.
+         */
+        virtual void NotifyAll() = 0;
+    };
+
+  protected:
+    sqlite3 *m_connection;
+
+    // Options
+    bool m_usingLucene;
+
+    // Stored data procedures
+    int m_dataCommandsCount;
+
+    // Synchronization object
+    std::unique_ptr<SynchronizationObject> m_synchronizationObject;
+
+    virtual void Connect(const std::string &address,
+                         Flag::Type = Flag::None, Flag::Option = Flag::RO);
+    virtual void Disconnect();
+
+    void TurnOnForeignKeys();
+
+    static SynchronizationObject *AllocDefaultSynchronizationObject();
+
+  public:
+    /**
+     * Open SQL connection
+     *
+     * Synchronization is archieved by using provided asynchronization object.
+     * If synchronizationObject is set to NULL, so synchronization is performed.
+     * Ownership of the synchronization object is transfered to sql connection
+     * object.
+     *
+     * @param address Database file name
+     * @param flags Open flags
+     * @param synchronizationObject A synchronization object to use.
+     */
+    explicit SqlConnection(const std::string &address = std::string(),
+                           Flag::Type flags = Flag::None,
+                           Flag::Option options = Flag::RO,
+                           SynchronizationObject *synchronizationObject =
+                               AllocDefaultSynchronizationObject());
+
+    /**
+     * Destructor
+     */
+    virtual ~SqlConnection();
+
+    /**
+     * Execute SQL command without result
+     *
+     * @param format
+     * @param ...
+     */
+    void ExecCommand(const char *format, ...) DPL_DEPRECATED_WITH_MESSAGE(
+            "To prevent sql injection do not use this \
+             method for direct sql execution");
+
+    /**
+     * Execute BEGIN; command to start new transaction
+     *
+     */
+    void BeginTransaction();
+
+    /**
+     * Execute ROLLBACK; command to discard changes made
+     *
+     */
+    void RollbackTransaction();
+
+    /**
+     * Execute COMMIT; command to commit changes in database
+     *
+     */
+    void CommitTransaction();
+
+    /**
+     * Prepare stored procedure
+     *
+     * @param format SQL statement
+     * @return Data command representing stored procedure
+     */
+    DataCommandAutoPtr PrepareDataCommand(const char *format, ...);
+
+    /**
+     * Check whether given table exists
+     *
+     * @param tableName Name of the table to check
+     * @return True if given table name exists
+     */
+    bool CheckTableExist(const char *tableName);
+
+    /**
+     * Get last insert operation new row id
+     *
+     * @return Row ID
+     */
+    RowID GetLastInsertRowID() const;
+};
+} // namespace DB
+} // namespace DPL
+
+#endif // DPL_SQL_CONNECTION_H
diff --git a/commons/modules/db/include/dpl/db/thread_database_support.h b/commons/modules/db/include/dpl/db/thread_database_support.h
new file mode 100644 (file)
index 0000000..04ec923
--- /dev/null
@@ -0,0 +1,300 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    thread_database_support.h
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk)
+ * @version 1.0
+ * @brief   This file contains the declaration of thread database support
+ */
+
+#ifndef DPL_THREAD_DATABASE_SUPPORT_H
+#define DPL_THREAD_DATABASE_SUPPORT_H
+
+#include <string>
+#include <dpl/db/sql_connection.h>
+#include <dpl/db/orm_interface.h>
+#include <dpl/thread.h>
+#include <dpl/assert.h>
+#include <stdint.h>
+
+namespace DPL {
+namespace DB {
+/**
+ * Thread database support
+ *
+ * Associate database connection with thread lifecycle
+ *
+ */
+
+class ThreadDatabaseSupport :
+    public DPL::DB::ORM::IOrmInterface
+{
+  private:
+    typedef DPL::DB::SqlConnection *SqlConnectionPtr;
+    typedef DPL::ThreadLocalVariable<SqlConnectionPtr> TLVSqlConnectionPtr;
+    typedef DPL::ThreadLocalVariable<size_t> TLVSizeT;
+    typedef DPL::ThreadLocalVariable<bool> TLVBool;
+
+    TLVSqlConnectionPtr m_connection;
+    TLVBool m_linger;
+    TLVSizeT m_refCounter;
+    TLVSizeT m_transactionDepth;
+    TLVSizeT m_attachCount;
+    TLVBool m_transactionCancel;
+    std::string m_address;
+    DPL::DB::SqlConnection::Flag::Type m_flags;
+
+    TLVSqlConnectionPtr &Connection()
+    {
+        return m_connection;
+    }
+
+    TLVBool &Linger()
+    {
+        return m_linger;
+    }
+
+    TLVSizeT &RefCounter()
+    {
+        return m_refCounter;
+    }
+
+    TLVSizeT &TransactionDepth()
+    {
+        return m_transactionDepth;
+    }
+
+    TLVSizeT &AttachCount()
+    {
+        return m_attachCount;
+    }
+
+    TLVBool &TransactionCancel()
+    {
+        return m_transactionCancel;
+    }
+
+    void CheckedConnectionDelete()
+    {
+        Assert(!Connection().IsNull());
+        Assert(*Linger() == true);
+
+        if (*RefCounter() > 0 || *AttachCount() > 0) {
+            return;
+        }
+
+        // Destroy connection
+        LogDebug("Destroying thread database connection: " << m_address);
+
+        delete *Connection();
+
+        // Blocking destroy
+        Connection().GuardValue(false);
+        Linger().GuardValue(false);
+        RefCounter().GuardValue(false);
+        TransactionCancel().GuardValue(false);
+        TransactionDepth().GuardValue(false);
+        AttachCount().GuardValue(false);
+
+        Connection().Reset();
+        Linger().Reset();
+        RefCounter().Reset();
+        TransactionCancel().Reset();
+        TransactionDepth().Reset();
+        AttachCount().Reset();
+    }
+
+    void TransactionUnref()
+    {
+        LogPedantic("Unref transaction");
+
+        if (--(*TransactionDepth()) == 0) {
+            LogPedantic("Transaction is finalized");
+
+            if (*TransactionCancel()) {
+                LogPedantic("Transaction will be rolled back");
+                (*Connection())->RollbackTransaction();
+            } else {
+                LogPedantic("Transaction will be commited");
+                (*Connection())->CommitTransaction();
+            }
+        }
+    }
+
+  public:
+    ThreadDatabaseSupport(const std::string &address,
+                          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)
+    {
+        Linger() = false;
+
+        if (!Connection().IsNull()) {
+            // Add reference
+            ++*AttachCount();
+            return;
+        }
+
+        // Initialize SQL connection described in traits
+        LogDebug("Attaching thread database connection: " << m_address);
+
+        Connection() = new DPL::DB::SqlConnection(
+                m_address.c_str(), m_flags, options);
+
+        RefCounter() = 0;
+
+        AttachCount() = 1;
+
+        //Init Transaction related variables
+        TransactionDepth() = 0;
+        TransactionCancel() = false;
+
+        // Blocking destroy
+        Connection().GuardValue(true);
+        Linger().GuardValue(true);
+        RefCounter().GuardValue(true);
+        TransactionDepth().GuardValue(true);
+        AttachCount().GuardValue(true);
+        TransactionCancel().GuardValue(true);
+    }
+
+    void DetachFromThread()
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        // Remove reference
+        --*AttachCount();
+
+        if (*AttachCount() > 0) {
+            return;
+        }
+
+        // It must not be in linger state yet
+        Assert(*Linger() == false);
+
+        LogDebug("Detaching thread database connection: " << m_address);
+
+        // Enter linger state
+        *Linger() = true;
+
+        // Checked delete
+        CheckedConnectionDelete();
+    }
+
+    bool IsAttached()
+    {
+        return !AttachCount().IsNull() && *AttachCount() > 0;
+    }
+
+    DPL::DB::SqlConnection::DataCommand *AllocDataCommand(
+        const std::string &statement)
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        // Calling thread must not be in linger state
+        Assert(*Linger() == false);
+
+        // Add reference
+        ++*RefCounter();
+
+        // Create new unmanaged data command
+        return (*Connection())->PrepareDataCommand(statement.c_str()).release();
+    }
+
+    void FreeDataCommand(DPL::DB::SqlConnection::DataCommand *command)
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        // Delete data command
+        delete command;
+
+        // Unreference SQL connection
+        --*RefCounter();
+
+        // If it is linger state, connection may be destroyed
+        if (*Linger() == true) {
+            CheckedConnectionDelete();
+        }
+    }
+
+    void TransactionBegin()
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        LogPedantic("Begin transaction");
+
+        // Addref transaction
+        if (++(*TransactionDepth()) == 1) {
+            LogPedantic("Transaction is initialized");
+
+            TransactionCancel() = false;
+            (*Connection())->BeginTransaction();
+        }
+    }
+
+    void TransactionCommit()
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        LogPedantic("Commit transaction");
+
+        // Unref transation
+        TransactionUnref();
+    }
+
+    void TransactionRollback()
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        // Cancel and unref transaction
+        TransactionCancel() = true;
+        TransactionUnref();
+    }
+
+    DPL::DB::SqlConnection::RowID GetLastInsertRowID()
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        return (*Connection())->GetLastInsertRowID();
+    }
+
+    bool CheckTableExist(const char *name)
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        return (*Connection())->CheckTableExist(name);
+    }
+};
+}
+}
+
+#endif // DPL_THREAD_DATABASE_SUPPORT_H
diff --git a/commons/modules/db/src/naive_synchronization_object.cpp b/commons/modules/db/src/naive_synchronization_object.cpp
new file mode 100644 (file)
index 0000000..1ac71ca
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        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
+ */
+#include <stddef.h>
+#include <dpl/db/naive_synchronization_object.h>
+#include <dpl/thread.h>
+
+namespace {
+    unsigned int seed = time(NULL);
+}
+
+namespace DPL {
+namespace DB {
+void NaiveSynchronizationObject::Synchronize()
+{
+    // Sleep for about 10ms - 30ms
+    Thread::MiliSleep(10 + rand_r(&seed) % 20);
+}
+
+void NaiveSynchronizationObject::NotifyAll()
+{
+    // No need to inform about anything
+}
+} // namespace DB
+} // namespace DPL
diff --git a/commons/modules/db/src/orm.cpp b/commons/modules/db/src/orm.cpp
new file mode 100644 (file)
index 0000000..c69415d
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        orm.cpp
+ * @author      Bartosz Janiak (b.janiak@samsung.com)
+ * @version     1.0
+ * @brief       Static definitions and function template specialziations of
+ * DPL-ORM.
+ */
+#include <stddef.h>
+#include <dpl/db/orm.h>
+
+namespace DPL {
+namespace DB {
+namespace ORM {
+namespace RelationTypes {
+const char Equal[] = "=";
+const char LessThan[] = "<";
+const char And[] = "AND";
+const char Or[] = "OR";
+const char Is[] = "IS";
+const char In[] = "IN";
+}
+
+template<>
+int GetColumnFromCommand<int>(ColumnIndex columnIndex,
+                              DataCommand *command)
+{
+    return command->GetColumnInteger(columnIndex);
+}
+
+template<>
+DPL::String GetColumnFromCommand<DPL::String>(ColumnIndex columnIndex,
+                                              DataCommand *command)
+{
+    return DPL::FromUTF8String(command->GetColumnString(columnIndex));
+}
+
+template<>
+OptionalInteger GetColumnFromCommand<OptionalInteger>(ColumnIndex columnIndex,
+                                                      DataCommand *command)
+{
+    return command->GetColumnOptionalInteger(columnIndex);
+}
+
+template<>
+OptionalString GetColumnFromCommand<OptionalString>(ColumnIndex columnIndex,
+                                                    DataCommand *command)
+{
+    return command->GetColumnOptionalString(columnIndex);
+}
+
+template<>
+double GetColumnFromCommand<double>(ColumnIndex columnIndex,
+                                    DataCommand *command)
+{
+    return command->GetColumnDouble(columnIndex);
+}
+
+void DataCommandUtils::BindArgument(DataCommand *command,
+                                    ArgumentIndex index,
+                                    int argument)
+{
+    command->BindInteger(index, argument);
+}
+
+void DataCommandUtils::BindArgument(DataCommand *command,
+                                    ArgumentIndex index,
+                                    const OptionalInteger& argument)
+{
+    command->BindInteger(index, argument);
+}
+
+void DataCommandUtils::BindArgument(DataCommand *command,
+                                    ArgumentIndex index,
+                                    const DPL::String& argument)
+{
+    command->BindString(index, argument);
+}
+
+void DataCommandUtils::BindArgument(DataCommand *command,
+                                    ArgumentIndex index,
+                                    const OptionalString& argument)
+{
+    command->BindString(index, argument);
+}
+}
+}
+}
diff --git a/commons/modules/db/src/sql_connection.cpp b/commons/modules/db/src/sql_connection.cpp
new file mode 100644 (file)
index 0000000..607e6d3
--- /dev/null
@@ -0,0 +1,870 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        sql_connection.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of SQL connection
+ */
+#include <stddef.h>
+#include <dpl/db/sql_connection.h>
+#include <dpl/db/naive_synchronization_object.h>
+#include <dpl/free_deleter.h>
+#include <memory>
+#include <dpl/noncopyable.h>
+#include <dpl/assert.h>
+#include <db-util.h>
+#include <unistd.h>
+#include <cstdio>
+#include <cstdarg>
+
+namespace DPL {
+namespace DB {
+namespace // anonymous
+{
+class ScopedNotifyAll :
+    public Noncopyable
+{
+  private:
+    SqlConnection::SynchronizationObject *m_synchronizationObject;
+
+  public:
+    explicit ScopedNotifyAll(
+        SqlConnection::SynchronizationObject *synchronizationObject) :
+        m_synchronizationObject(synchronizationObject)
+    {}
+
+    ~ScopedNotifyAll()
+    {
+        if (!m_synchronizationObject) {
+            return;
+        }
+
+        LogPedantic("Notifying after successful synchronize");
+        m_synchronizationObject->NotifyAll();
+    }
+};
+} // namespace anonymous
+
+SqlConnection::DataCommand::DataCommand(SqlConnection *connection,
+                                        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 (;;) {
+        int ret = sqlite3_prepare_v2(connection->m_connection,
+                                     buffer, strlen(buffer),
+                                     &m_stmt, NULL);
+
+        if (ret == SQLITE_OK) {
+            LogPedantic("Data command prepared successfuly");
+            break;
+        } else if (ret == SQLITE_BUSY) {
+            LogPedantic("Collision occurred while preparing SQL command");
+
+            // Synchronize if synchronization object is available
+            if (connection->m_synchronizationObject) {
+                LogPedantic("Performing synchronization");
+                connection->m_synchronizationObject->Synchronize();
+                continue;
+            }
+
+            // No synchronization object defined. Fail.
+        }
+
+        // Fatal error
+        const char *error = sqlite3_errmsg(m_masterConnection->m_connection);
+
+        LogPedantic("SQL prepare data command failed");
+        LogPedantic("    Statement: " << buffer);
+        LogPedantic("    Error: " << error);
+
+        ThrowMsg(Exception::SyntaxError, error);
+    }
+
+    LogPedantic("Prepared data command: " << buffer);
+
+    // Increment stored data command count
+    ++m_masterConnection->m_dataCommandsCount;
+}
+
+SqlConnection::DataCommand::~DataCommand()
+{
+    LogPedantic("SQL data command finalizing");
+
+    if (sqlite3_finalize(m_stmt) != SQLITE_OK) {
+        LogPedantic("Failed to finalize data command");
+    }
+
+    // Decrement stored data command count
+    --m_masterConnection->m_dataCommandsCount;
+}
+
+void SqlConnection::DataCommand::CheckBindResult(int result)
+{
+    if (result != SQLITE_OK) {
+        const char *error = sqlite3_errmsg(
+                m_masterConnection->m_connection);
+
+        LogPedantic("Failed to bind SQL statement parameter");
+        LogPedantic("    Error: " << error);
+
+        ThrowMsg(Exception::SyntaxError, error);
+    }
+}
+
+void SqlConnection::DataCommand::BindNull(
+    SqlConnection::ArgumentIndex position)
+{
+    CheckBindResult(sqlite3_bind_null(m_stmt, position));
+    LogPedantic("SQL data command bind null: ["
+                << position << "]");
+}
+
+void SqlConnection::DataCommand::BindInteger(
+    SqlConnection::ArgumentIndex position,
+    int value)
+{
+    CheckBindResult(sqlite3_bind_int(m_stmt, position, value));
+    LogPedantic("SQL data command bind integer: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindInt8(
+    SqlConnection::ArgumentIndex position,
+    int8_t value)
+{
+    CheckBindResult(sqlite3_bind_int(m_stmt, position,
+                                     static_cast<int>(value)));
+    LogPedantic("SQL data command bind int8: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindInt16(
+    SqlConnection::ArgumentIndex position,
+    int16_t value)
+{
+    CheckBindResult(sqlite3_bind_int(m_stmt, position,
+                                     static_cast<int>(value)));
+    LogPedantic("SQL data command bind int16: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindInt32(
+    SqlConnection::ArgumentIndex position,
+    int32_t value)
+{
+    CheckBindResult(sqlite3_bind_int(m_stmt, position,
+                                     static_cast<int>(value)));
+    LogPedantic("SQL data command bind int32: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindInt64(
+    SqlConnection::ArgumentIndex position,
+    int64_t value)
+{
+    CheckBindResult(sqlite3_bind_int64(m_stmt, position,
+                                       static_cast<sqlite3_int64>(value)));
+    LogPedantic("SQL data command bind int64: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindFloat(
+    SqlConnection::ArgumentIndex position,
+    float value)
+{
+    CheckBindResult(sqlite3_bind_double(m_stmt, position,
+                                        static_cast<double>(value)));
+    LogPedantic("SQL data command bind float: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindDouble(
+    SqlConnection::ArgumentIndex position,
+    double value)
+{
+    CheckBindResult(sqlite3_bind_double(m_stmt, position, value));
+    LogPedantic("SQL data command bind double: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindString(
+    SqlConnection::ArgumentIndex position,
+    const char *value)
+{
+    if (!value) {
+        BindNull(position);
+        return;
+    }
+
+    // Assume that text may disappear
+    CheckBindResult(sqlite3_bind_text(m_stmt, position,
+                                      value, strlen(value),
+                                      SQLITE_TRANSIENT));
+
+    LogPedantic("SQL data command bind string: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindString(
+    SqlConnection::ArgumentIndex position,
+    const String &value)
+{
+    BindString(position, ToUTF8String(value).c_str());
+}
+
+void SqlConnection::DataCommand::BindInteger(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<int> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindInteger(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindInt8(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<int8_t> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindInt8(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindInt16(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<int16_t> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindInt16(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindInt32(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<int32_t> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindInt32(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindInt64(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<int64_t> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindInt64(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindFloat(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<float> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindFloat(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindDouble(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<double> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindDouble(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindString(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<String> &value)
+{
+    if (!!value) {
+        BindString(position, ToUTF8String(*value).c_str());
+    } else {
+        BindNull(position);
+    }
+}
+
+bool SqlConnection::DataCommand::Step()
+{
+    // Notify all after potentially synchronized database connection access
+    ScopedNotifyAll notifyAll(
+        m_masterConnection->m_synchronizationObject.get());
+
+    for (;;) {
+        int ret = sqlite3_step(m_stmt);
+
+        if (ret == SQLITE_ROW) {
+            LogPedantic("SQL data command step ROW");
+            return true;
+        } else if (ret == SQLITE_DONE) {
+            LogPedantic("SQL data command step DONE");
+            return false;
+        } else if (ret == SQLITE_BUSY) {
+            LogPedantic("Collision occurred while executing SQL command");
+
+            // Synchronize if synchronization object is available
+            if (m_masterConnection->m_synchronizationObject) {
+                LogPedantic("Performing synchronization");
+
+                m_masterConnection->
+                    m_synchronizationObject->Synchronize();
+
+                continue;
+            }
+
+            // No synchronization object defined. Fail.
+        }
+
+        // Fatal error
+        const char *error = sqlite3_errmsg(m_masterConnection->m_connection);
+
+        LogPedantic("SQL step data command failed");
+        LogPedantic("    Error: " << error);
+
+        ThrowMsg(Exception::InternalError, error);
+    }
+}
+
+void SqlConnection::DataCommand::Reset()
+{
+    /*
+     * According to:
+     * http://www.sqlite.org/c3ref/stmt.html
+     *
+     * if last sqlite3_step command on this stmt returned an error,
+     * then sqlite3_reset will return that error, althought it is not an error.
+     * So sqlite3_reset allways succedes.
+     */
+    sqlite3_reset(m_stmt);
+
+    LogPedantic("SQL data command reset");
+}
+
+void SqlConnection::DataCommand::CheckColumnIndex(
+    SqlConnection::ColumnIndex column)
+{
+    if (column < 0 || column >= sqlite3_column_count(m_stmt)) {
+        ThrowMsg(Exception::InvalidColumn, "Column index is out of bounds");
+    }
+}
+
+bool SqlConnection::DataCommand::IsColumnNull(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column type: [" << column << "]");
+    CheckColumnIndex(column);
+    return sqlite3_column_type(m_stmt, column) == SQLITE_NULL;
+}
+
+int SqlConnection::DataCommand::GetColumnInteger(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column integer: [" << column << "]");
+    CheckColumnIndex(column);
+    int value = sqlite3_column_int(m_stmt, column);
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+int8_t SqlConnection::DataCommand::GetColumnInt8(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column int8: [" << column << "]");
+    CheckColumnIndex(column);
+    int8_t value = static_cast<int8_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+int16_t SqlConnection::DataCommand::GetColumnInt16(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column int16: [" << column << "]");
+    CheckColumnIndex(column);
+    int16_t value = static_cast<int16_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+int32_t SqlConnection::DataCommand::GetColumnInt32(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column int32: [" << column << "]");
+    CheckColumnIndex(column);
+    int32_t value = static_cast<int32_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+int64_t SqlConnection::DataCommand::GetColumnInt64(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column int64: [" << column << "]");
+    CheckColumnIndex(column);
+    int64_t value = static_cast<int64_t>(sqlite3_column_int64(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+float SqlConnection::DataCommand::GetColumnFloat(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column float: [" << column << "]");
+    CheckColumnIndex(column);
+    float value = static_cast<float>(sqlite3_column_double(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+double SqlConnection::DataCommand::GetColumnDouble(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column double: [" << column << "]");
+    CheckColumnIndex(column);
+    double value = sqlite3_column_double(m_stmt, column);
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+std::string SqlConnection::DataCommand::GetColumnString(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column string: [" << column << "]");
+    CheckColumnIndex(column);
+
+    const char *value = reinterpret_cast<const char *>(
+            sqlite3_column_text(m_stmt, column));
+
+    LogPedantic("Value: " << (value ? value : "NULL"));
+
+    if (value == NULL) {
+        return std::string();
+    }
+
+    return std::string(value);
+}
+
+boost::optional<int> SqlConnection::DataCommand::GetColumnOptionalInteger(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional integer: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<int>();
+    }
+    int value = sqlite3_column_int(m_stmt, column);
+    LogPedantic("    Value: " << value);
+    return boost::optional<int>(value);
+}
+
+boost::optional<int8_t> SqlConnection::DataCommand::GetColumnOptionalInt8(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional int8: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<int8_t>();
+    }
+    int8_t value = static_cast<int8_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return boost::optional<int8_t>(value);
+}
+
+boost::optional<int16_t> SqlConnection::DataCommand::GetColumnOptionalInt16(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional int16: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<int16_t>();
+    }
+    int16_t value = static_cast<int16_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return boost::optional<int16_t>(value);
+}
+
+boost::optional<int32_t> SqlConnection::DataCommand::GetColumnOptionalInt32(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional int32: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<int32_t>();
+    }
+    int32_t value = static_cast<int32_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return boost::optional<int32_t>(value);
+}
+
+boost::optional<int64_t> SqlConnection::DataCommand::GetColumnOptionalInt64(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional int64: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<int64_t>();
+    }
+    int64_t value = static_cast<int64_t>(sqlite3_column_int64(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return boost::optional<int64_t>(value);
+}
+
+boost::optional<float> SqlConnection::DataCommand::GetColumnOptionalFloat(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional float: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<float>();
+    }
+    float value = static_cast<float>(sqlite3_column_double(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return boost::optional<float>(value);
+}
+
+boost::optional<double> SqlConnection::DataCommand::GetColumnOptionalDouble(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional double: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<double>();
+    }
+    double value = sqlite3_column_double(m_stmt, column);
+    LogPedantic("    Value: " << value);
+    return boost::optional<double>(value);
+}
+
+boost::optional<String> SqlConnection::DataCommand::GetColumnOptionalString(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional string: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<String>();
+    }
+    const char *value = reinterpret_cast<const char *>(
+            sqlite3_column_text(m_stmt, column));
+    LogPedantic("Value: " << value);
+    String s = FromUTF8String(value);
+    return boost::optional<String>(s);
+}
+
+void SqlConnection::Connect(const std::string &address,
+                            Flag::Type type,
+                            Flag::Option flag)
+{
+    if (m_connection != NULL) {
+        LogPedantic("Already connected.");
+        return;
+    }
+    LogPedantic("Connecting to DB: " << address << "...");
+
+    // Connect to database
+    int result = -1;
+    int retry = 5;
+    while( result != SQLITE_OK){
+        if (type & Flag::UseLucene) {
+            result = db_util_open_with_options(
+                    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);
+
+            m_usingLucene = false;
+            LogPedantic("Lucene index disabled");
+        }
+
+        if (result == SQLITE_OK) {
+            LogPedantic("Connected to DB");
+        } else {
+            LogPedantic("Failed to connect to DB! ret="<<result);
+            if( retry-- <= 0 )
+                ThrowMsg(Exception::ConnectionBroken, address);
+        }
+    }
+
+    // Enable foreign keys
+    TurnOnForeignKeys();
+}
+
+void SqlConnection::Disconnect()
+{
+    if (m_connection == NULL) {
+        LogPedantic("Already disconnected.");
+        return;
+    }
+
+    LogPedantic("Disconnecting from DB...");
+
+    // All stored data commands must be deleted before disconnect
+    AssertMsg(m_dataCommandsCount == 0,
+           "All stored procedures must be deleted"
+           " before disconnecting SqlConnection");
+
+    int result;
+
+    if (m_usingLucene) {
+        result = db_util_close(m_connection);
+    } else {
+        result = sqlite3_close(m_connection);
+    }
+
+    if (result != SQLITE_OK) {
+        const char *error = sqlite3_errmsg(m_connection);
+        LogPedantic("SQL close failed");
+        LogPedantic("    Error: " << error);
+        Throw(Exception::InternalError);
+    }
+
+    m_connection = NULL;
+
+    LogPedantic("Disconnected from DB");
+}
+
+bool SqlConnection::CheckTableExist(const char *tableName)
+{
+    if (m_connection == NULL) {
+        LogPedantic("Cannot execute command. Not connected to DB!");
+        return false;
+    }
+
+    DataCommandAutoPtr command =
+        PrepareDataCommand("select tbl_name from sqlite_master where name=?;");
+
+    command->BindString(1, tableName);
+
+    if (!command->Step()) {
+        LogPedantic("No matching records in table");
+        return false;
+    }
+
+    return command->GetColumnString(0) == 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)
+{
+    LogPedantic("Opening database connection to: " << address);
+
+    // Connect to DB
+    SqlConnection::Connect(address, flag, option);
+
+    if (!m_synchronizationObject) {
+        LogPedantic("No synchronization object defined");
+    }
+}
+
+SqlConnection::~SqlConnection()
+{
+    LogPedantic("Closing database connection");
+
+    // Disconnect from DB
+    Try
+    {
+        SqlConnection::Disconnect();
+    }
+    Catch(Exception::Base)
+    {
+        LogPedantic("Failed to disconnect from database");
+    }
+}
+
+void SqlConnection::ExecCommand(const char *format, ...)
+{
+    if (m_connection == NULL) {
+        LogPedantic("Cannot execute command. Not connected to DB!");
+        return;
+    }
+
+    if (format == NULL) {
+        LogPedantic("Null query!");
+        ThrowMsg(Exception::SyntaxError, "Null statement");
+    }
+
+    char *rawBuffer;
+
+    va_list args;
+    va_start(args, format);
+
+    if (vasprintf(&rawBuffer, format, args) == -1) {
+        rawBuffer = NULL;
+    }
+
+    va_end(args);
+
+    std::unique_ptr<char[],free_deleter> buffer(rawBuffer);
+
+    if (!buffer) {
+        LogPedantic("Failed to allocate statement string");
+        return;
+    }
+
+    LogPedantic("Executing SQL command: " << buffer.get());
+
+    // Notify all after potentially synchronized database connection access
+    ScopedNotifyAll notifyAll(m_synchronizationObject.get());
+
+    for (;;) {
+        char *errorBuffer;
+
+        int ret = sqlite3_exec(m_connection,
+                               buffer.get(),
+                               NULL,
+                               NULL,
+                               &errorBuffer);
+
+        std::string errorMsg;
+
+        // Take allocated error buffer
+        if (errorBuffer != NULL) {
+            errorMsg = errorBuffer;
+            sqlite3_free(errorBuffer);
+        }
+
+        if (ret == SQLITE_OK) {
+            return;
+        }
+
+        if (ret == SQLITE_BUSY) {
+            LogPedantic("Collision occurred while executing SQL command");
+
+            // Synchronize if synchronization object is available
+            if (m_synchronizationObject) {
+                LogPedantic("Performing synchronization");
+                m_synchronizationObject->Synchronize();
+                continue;
+            }
+
+            // No synchronization object defined. Fail.
+        }
+
+        // Fatal error
+        LogPedantic("Failed to execute SQL command. Error: " << errorMsg);
+        ThrowMsg(Exception::SyntaxError, errorMsg);
+    }
+}
+
+SqlConnection::DataCommandAutoPtr SqlConnection::PrepareDataCommand(
+    const char *format,
+    ...)
+{
+    if (m_connection == NULL) {
+        LogPedantic("Cannot execute data command. Not connected to DB!");
+        return DataCommandAutoPtr();
+    }
+
+    char *rawBuffer;
+
+    va_list args;
+    va_start(args, format);
+
+    if (vasprintf(&rawBuffer, format, args) == -1) {
+        rawBuffer = NULL;
+    }
+
+    va_end(args);
+
+    std::unique_ptr<char[],free_deleter> buffer(rawBuffer);
+
+    if (!buffer) {
+        LogPedantic("Failed to allocate statement string");
+        return DataCommandAutoPtr();
+    }
+
+    LogPedantic("Executing SQL data command: " << buffer.get());
+
+    return DataCommandAutoPtr(new DataCommand(this, buffer.get()));
+}
+
+SqlConnection::RowID SqlConnection::GetLastInsertRowID() const
+{
+    return static_cast<RowID>(sqlite3_last_insert_rowid(m_connection));
+}
+
+void SqlConnection::TurnOnForeignKeys()
+{
+    ExecCommand("PRAGMA foreign_keys = ON;");
+}
+
+void SqlConnection::BeginTransaction()
+{
+    ExecCommand("BEGIN;");
+}
+
+void SqlConnection::RollbackTransaction()
+{
+    ExecCommand("ROLLBACK;");
+}
+
+void SqlConnection::CommitTransaction()
+{
+    ExecCommand("COMMIT;");
+}
+
+SqlConnection::SynchronizationObject *
+SqlConnection::AllocDefaultSynchronizationObject()
+{
+    return new NaiveSynchronizationObject();
+}
+} // namespace DB
+} // namespace DPL
diff --git a/commons/modules/db/src/thread_database_support.cpp b/commons/modules/db/src/thread_database_support.cpp
new file mode 100644 (file)
index 0000000..101640f
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    thread_database_support.cpp
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk)
+ * @version 1.0
+ * @brief   This file contains the definition of thread database support
+ */
+#include <stddef.h>
+#include <dpl/db/thread_database_support.h>
\ No newline at end of file
diff --git a/commons/modules/log/config.cmake b/commons/modules/log/config.cmake
new file mode 100644 (file)
index 0000000..e4d3e37
--- /dev/null
@@ -0,0 +1,43 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+#
+# @file        config.cmake
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+SET(DPL_LOG_SOURCES
+    ${PROJECT_SOURCE_DIR}/modules/log/src/abstract_log_provider.cpp
+    ${PROJECT_SOURCE_DIR}/modules/log/src/dlog_log_provider.cpp
+    ${PROJECT_SOURCE_DIR}/modules/log/src/log.cpp
+    ${PROJECT_SOURCE_DIR}/modules/log/src/old_style_log_provider.cpp
+    PARENT_SCOPE
+)
+
+SET(DPL_LOG_HEADERS
+    ${PROJECT_SOURCE_DIR}/modules/log/include/dpl/log/abstract_log_provider.h
+    ${PROJECT_SOURCE_DIR}/modules/log/include/dpl/log/dlog_log_provider.h
+    ${PROJECT_SOURCE_DIR}/modules/log/include/dpl/log/log.h
+    ${PROJECT_SOURCE_DIR}/modules/log/include/dpl/log/old_style_log_provider.h
+    ${PROJECT_SOURCE_DIR}/modules/log/include/dpl/log/secure_log.h
+    PARENT_SCOPE
+)
+
+SET(DPL_LOG_INCLUDE_DIR
+    ${PROJECT_SOURCE_DIR}/modules/log/include/
+    ${PROJECT_SOURCE_DIR}/modules/core/include/
+    PARENT_SCOPE
+)
diff --git a/commons/modules/log/include/dpl/log/abstract_log_provider.h b/commons/modules/log/include/dpl/log/abstract_log_provider.h
new file mode 100644 (file)
index 0000000..62fa050
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        abstract_log_provider.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of abstract log provider
+ */
+#ifndef DPL_ABSTRACT_LOG_PROVIDER_H
+#define DPL_ABSTRACT_LOG_PROVIDER_H
+
+namespace DPL {
+namespace Log {
+class AbstractLogProvider
+{
+  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;
+
+  protected:
+    static const char *LocateSourceFileName(const char *filename);
+};
+}
+} // namespace DPL
+
+#endif // DPL_ABSTRACT_LOG_PROVIDER_H
diff --git a/commons/modules/log/include/dpl/log/dlog_log_provider.h b/commons/modules/log/include/dpl/log/dlog_log_provider.h
new file mode 100644 (file)
index 0000000..f23399a
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        dlog_log_provider.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of DLOG log provider
+ */
+#ifndef DPL_DLOG_LOG_PROVIDER_H
+#define DPL_DLOG_LOG_PROVIDER_H
+
+#include <dpl/log/abstract_log_provider.h>
+#include <dpl/free_deleter.h>
+#include <memory>
+#include <string>
+
+namespace DPL {
+namespace Log {
+class DLOGLogProvider :
+    public AbstractLogProvider
+{
+  private:
+    std::unique_ptr<char[],free_deleter> m_tag;
+
+    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);
+
+    // Set global Tag according to DLOG
+    void SetTag(const char *tag);
+};
+}
+} // namespace DPL
+
+#endif // DPL_DLOG_LOG_PROVIDER_H
diff --git a/commons/modules/log/include/dpl/log/log.h b/commons/modules/log/include/dpl/log/log.h
new file mode 100644 (file)
index 0000000..d4d95ed
--- /dev/null
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        log.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of log system
+ */
+#ifndef DPL_LOG_H
+#define DPL_LOG_H
+
+#include <dpl/singleton.h>
+#include <dpl/noncopyable.h>
+#include <dpl/log/abstract_log_provider.h>
+#include <dpl/log/dlog_log_provider.h>
+#include <dpl/log/old_style_log_provider.h>
+#include <sstream>
+#include <list>
+
+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
+{
+  private:
+    typedef std::list<AbstractLogProvider *> AbstractLogProviderPtrList;
+    AbstractLogProviderPtrList m_providers;
+
+    DLOGLogProvider *m_dlogProvider;
+    OldStyleLogProvider *m_oldStyleProvider;
+
+    bool m_isLoggingEnabled;
+
+  public:
+    bool IsLoggingEnabled() const;
+    LogSystem();
+    virtual ~LogSystem();
+
+    /**
+     * Log debug message
+     */
+    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);
+
+    /**
+     * Log warning message
+     */
+    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);
+
+    /**
+     * Log pedantic message
+     */
+    void Pedantic(const char *message,
+                  const char *filename,
+                  int line,
+                  const char *function);
+
+    /**
+     * Set default's DLOG provider Tag
+     */
+    void SetTag(const char *tag);
+
+    /**
+     * Add abstract provider to providers list
+     *
+     * @notice Ownership is transfered to LogSystem and deleted upon exit
+     */
+    void AddProvider(AbstractLogProvider *provider);
+
+    /**
+     * Remove abstract provider from providers list
+     */
+    void RemoveProvider(AbstractLogProvider *provider);
+};
+
+/*
+ * Replacement low overhead null logging class
+ */
+class NullStream
+{
+  public:
+    NullStream() {}
+
+    template <typename T>
+    NullStream& operator<<(const T&)
+    {
+        return *this;
+    }
+};
+
+/**
+ * Log system singleton
+ */
+typedef Singleton<LogSystem> LogSystemSingleton;
+}
+} // namespace DPL
+
+//
+// Log support
+//
+//
+
+#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)
+#else
+/* avoid warnings about unused variables */
+    #define DPL_MACRO_FOR_LOGGING(message, function)                           \
+    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)
+#define  LogError(message) DPL_MACRO_FOR_LOGGING(message, Error)
+#define  LogPedantic(message) DPL_MACRO_FOR_LOGGING(message, Pedantic)
+
+#endif // DPL_LOG_H
diff --git a/commons/modules/log/include/dpl/log/old_style_log_provider.h b/commons/modules/log/include/dpl/log/old_style_log_provider.h
new file mode 100644 (file)
index 0000000..70e308a
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        old_style_log_provider.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of old style log provider
+ */
+#ifndef DPL_OLD_STYLE_LOG_PROVIDER_H
+#define DPL_OLD_STYLE_LOG_PROVIDER_H
+
+#include <dpl/log/abstract_log_provider.h>
+#include <string>
+
+namespace DPL {
+namespace Log {
+class OldStyleLogProvider :
+    public AbstractLogProvider
+{
+  private:
+    bool m_showDebug;
+    bool m_showInfo;
+    bool m_showWarning;
+    bool m_showError;
+    bool m_showPedantic;
+    bool m_printStdErr;
+
+    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);
+    OldStyleLogProvider(bool showDebug,
+                        bool showInfo,
+                        bool showWarning,
+                        bool showError,
+                        bool showPedantic,
+                        bool printStdErr);
+    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);
+};
+}
+} // namespace DPL
+
+#endif // DPL_OLD_STYLE_LOG_PROVIDER_H
diff --git a/commons/modules/log/include/dpl/log/secure_log.h b/commons/modules/log/include/dpl/log/secure_log.h
new file mode 100644 (file)
index 0000000..6402c4f
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file       secure_log.h
+ * @author     Jihoon Chung(jihoon.chung@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef DPL_SECURE_LOG_H
+#define DPL_SECURE_LOG_H
+
+#include <dlog.h>
+
+#define COLOR_ERROR   "\e[1;31m"
+#define COLOR_WARNING "\e[2;31m"
+#define COLOR_END     "\e[0m"
+#define COLOR_TAG     "\e[0m"
+
+// default TAG
+#undef LOG_TAG
+#define LOG_TAG "WRT_UNDEFINED"
+
+#ifdef WRT_LOG
+#undef LOG_TAG
+#define LOG_TAG "WRT"
+#undef COLOR_TAG
+#define COLOR_TAG "\e[1;32m"
+#endif
+
+#ifdef WRT_BUNDLE_LOG
+#undef LOG_TAG
+#define LOG_TAG "WRT_BUNDLE"
+#undef COLOR_TAG
+#define COLOR_TAG "\e[1;34m"
+#endif
+
+#ifdef WRT_PLUGINS_COMMON_LOG
+#undef LOG_TAG
+#define LOG_TAG "WRT_PLUGINS/COMMON"
+#undef COLOR_TAG
+#define COLOR_TAG "\e[1;36m"
+#endif
+
+#ifdef WRT_PLUGINS_WIDGET_LOG
+#undef LOG_TAG
+#define LOG_TAG "WRT_PLUGINS/WIDGET"
+#undef COLOR_TAG
+#define COLOR_TAG "\e[1;35m"
+#endif
+
+#ifdef WRT_INSTALLER_LOG
+#undef LOG_TAG
+#define LOG_TAG "WRT_INSTALLER"
+#undef COLOR_TAG
+#define COLOR_TAG "\e[1;32m"
+#endif
+
+#ifndef SECURE_SLOGD
+#define SECURE_SLOGD(fmt, arg...) SLOGD(fmt,##arg)
+#endif
+
+#ifndef SECURE_SLOGW
+#define SECURE_SLOGW(fmt, arg...) SLOGW(fmt,##arg)
+#endif
+
+#ifndef SECURE_SLOGE
+#define SECURE_SLOGE(fmt, arg...) SLOGE(fmt,##arg)
+#endif
+
+#undef _D
+#define _D(fmt, arg ...) SECURE_SLOGD(COLOR_TAG fmt COLOR_END,##arg)
+#undef _W
+#define _W(fmt, arg ...) SECURE_SLOGW(COLOR_WARNING fmt COLOR_END,##arg)
+#undef _E
+#define _E(fmt, arg ...) SECURE_SLOGE(COLOR_ERROR fmt COLOR_END,##arg)
+
+#endif // DPL_SECURE_LOG_H
+
diff --git a/commons/modules/log/src/abstract_log_provider.cpp b/commons/modules/log/src/abstract_log_provider.cpp
new file mode 100644 (file)
index 0000000..a03f8a0
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        abstract_log_provider.cpp
+ * @author      Pawel Sikorski (p.sikorski@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of abstract log provider
+ */
+#include <stddef.h>
+#include <dpl/log/abstract_log_provider.h>
+#include <cstring>
+
+namespace DPL {
+namespace Log {
+const char *AbstractLogProvider::LocateSourceFileName(const char *filename)
+{
+    const char *ptr = strrchr(filename, '/');
+    return ptr != NULL ? ptr + 1 : filename;
+}
+}
+}
diff --git a/commons/modules/log/src/dlog_log_provider.cpp b/commons/modules/log/src/dlog_log_provider.cpp
new file mode 100644 (file)
index 0000000..f4fa0c9
--- /dev/null
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        dlog_log_provider.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of DLOG log provider
+ */
+#include <stddef.h>
+#include <dpl/log/dlog_log_provider.h>
+#include <cstring>
+#include <sstream>
+#include <dlog.h>
+
+#ifdef SECURE_LOG
+    #define INTERNAL_DLP_LOG_ SECURE_LOG
+#else
+    #define INTERNAL_DLP_LOG_ LOG
+#endif
+
+/*
+ * The __extension__ keyword in the following define is required because
+ * macros used here from dlog.h use non-standard extension that cause
+ * gcc to show unwanted warnings when compiling with -pedantic switch.
+ */
+#define INTERNAL_DLP_LOG __extension__ INTERNAL_DLP_LOG_
+
+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;
+
+    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)
+{
+    INTERNAL_DLP_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)
+{
+    INTERNAL_DLP_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)
+{
+    INTERNAL_DLP_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)
+{
+    INTERNAL_DLP_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)
+{
+    INTERNAL_DLP_LOG(LOG_DEBUG, "DPL", "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+}
+} // namespace DPL
+
+#undef INTERNAL_DLP_LOG
+#undef INTERNAL_DLP_LOG_
+
diff --git a/commons/modules/log/src/log.cpp b/commons/modules/log/src/log.cpp
new file mode 100644 (file)
index 0000000..7c0ebc2
--- /dev/null
@@ -0,0 +1,222 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        log.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of log system
+ */
+#include <stddef.h>
+#include <dpl/log/log.h>
+#include <dpl/singleton_impl.h>
+
+IMPLEMENT_SINGLETON(DPL::Log::LogSystem)
+
+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_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))
+{
+    bool oldStyleLogs = false;
+    bool oldStyleDebugLogs = true;
+    bool oldStyleInfoLogs = true;
+    bool oldStyleWarningLogs = true;
+    bool oldStyleErrorLogs = true;
+    bool oldStylePedanticLogs = false;
+
+    // Check environment settings about pedantic logs
+    const char *value = getenv(OLD_STYLE_LOGS_ENV_NAME);
+
+    if (value != NULL && !strcmp(value, "1")) {
+        oldStyleLogs = true;
+    }
+
+    value = getenv(OLD_STYLE_PEDANTIC_LOGS_ENV_NAME);
+
+    if (value != NULL && !strcmp(value, "1")) {
+        oldStylePedanticLogs = true;
+    }
+
+    value = getenv(OLD_STYLE_LOGS_MASK_ENV_NAME);
+
+    if (value != NULL) {
+        size_t len = strlen(value);
+
+        if (len >= 1) {
+            if (value[0] == '0') {
+                oldStyleDebugLogs = false;
+            } else if (value[0] == '1') {
+                oldStyleDebugLogs = true;
+            }
+        }
+
+        if (len >= 2) {
+            if (value[1] == '0') {
+                oldStyleInfoLogs = false;
+            } else if (value[1] == '1') {
+                oldStyleInfoLogs = true;
+            }
+        }
+
+        if (len >= 3) {
+            if (value[2] == '0') {
+                oldStyleWarningLogs = false;
+            } else if (value[2] == '1') {
+                oldStyleWarningLogs = true;
+            }
+        }
+
+        if (len >= 4) {
+            if (value[3] == '0') {
+                oldStyleErrorLogs = false;
+            } else if (value[3] == '1') {
+                oldStyleErrorLogs = true;
+            }
+        }
+    }
+
+    // Setup default DLOG and old style logging
+    if (oldStyleLogs) {
+        // Old style
+        m_oldStyleProvider = new OldStyleLogProvider(oldStyleDebugLogs,
+                                                     oldStyleInfoLogs,
+                                                     oldStyleWarningLogs,
+                                                     oldStyleErrorLogs,
+                                                     oldStylePedanticLogs);
+        AddProvider(m_oldStyleProvider);
+    } else {
+        // DLOG
+        m_dlogProvider = new DLOGLogProvider();
+        AddProvider(m_dlogProvider);
+    }
+}
+
+LogSystem::~LogSystem()
+{
+    // Delete all providers
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        delete *iterator;
+    }
+
+    m_providers.clear();
+
+    // And even default providers
+    m_dlogProvider = NULL;
+    m_oldStyleProvider = NULL;
+}
+
+void LogSystem::SetTag(const char* tag)
+{
+    if (m_dlogProvider != NULL) {
+        m_dlogProvider->SetTag(tag);
+    }
+}
+
+void LogSystem::AddProvider(AbstractLogProvider *provider)
+{
+    m_providers.push_back(provider);
+}
+
+void LogSystem::RemoveProvider(AbstractLogProvider *provider)
+{
+    m_providers.remove(provider);
+}
+
+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)
+    {
+        (*iterator)->Debug(message, filename, line, 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)
+    {
+        (*iterator)->Info(message, filename, line, 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)
+    {
+        (*iterator)->Warning(message, filename, line, 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)
+    {
+        (*iterator)->Error(message, filename, line, 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)
+    {
+        (*iterator)->Pedantic(message, filename, line, function);
+    }
+}
+}
+} // namespace DPL
diff --git a/commons/modules/log/src/old_style_log_provider.cpp b/commons/modules/log/src/old_style_log_provider.cpp
new file mode 100644 (file)
index 0000000..b8060dd
--- /dev/null
@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        old_style_log_provider.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of old style log provider
+ */
+#include <stddef.h>
+#include <dpl/log/old_style_log_provider.h>
+#include <dpl/colors.h>
+#include <cstdio>
+#include <cstring>
+#include <sstream>
+#include <sys/time.h>
+#include <unistd.h>
+
+namespace DPL {
+namespace Log {
+namespace // anonymous
+{
+using namespace DPL::Colors::Text;
+const char *DEBUG_BEGIN = GREEN_BEGIN;
+const char *DEBUG_END = GREEN_END;
+const char *INFO_BEGIN = CYAN_BEGIN;
+const char *INFO_END = CYAN_END;
+const char *ERROR_BEGIN = RED_BEGIN;
+const char *ERROR_END = RED_END;
+const char *WARNING_BEGIN = BOLD_GOLD_BEGIN;
+const char *WARNING_END = BOLD_GOLD_END;
+const char *PEDANTIC_BEGIN = PURPLE_BEGIN;
+const char *PEDANTIC_END = PURPLE_END;
+
+std::string GetFormattedTime()
+{
+    timeval tv;
+    tm localNowTime;
+
+    gettimeofday(&tv, NULL);
+    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<int>(tv.tv_usec / 1000));
+    return format;
+}
+} // namespace anonymous
+
+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<unsigned long>(pthread_self()) << "/" <<
+    static_cast<int>(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),
+    m_printStdErr(false)
+{}
+
+OldStyleLogProvider::OldStyleLogProvider(bool showDebug,
+                                         bool showInfo,
+                                         bool showWarning,
+                                         bool showError,
+                                         bool showPedantic,
+                                         bool printStdErr) :
+    m_showDebug(showDebug),
+    m_showInfo(showInfo),
+    m_showWarning(showWarning),
+    m_showError(showError),
+    m_showPedantic(showPedantic),
+    m_printStdErr(printStdErr)
+{}
+
+void OldStyleLogProvider::Debug(const char *message,
+                                const char *filename,
+                                int line,
+                                const char *function)
+{
+    if (m_showDebug) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", DEBUG_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), DEBUG_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", DEBUG_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), DEBUG_END);
+        }
+    }
+}
+
+void OldStyleLogProvider::Info(const char *message,
+                               const char *filename,
+                               int line,
+                               const char *function)
+{
+    if (m_showInfo) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", INFO_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), INFO_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", INFO_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), INFO_END);
+        }
+    }
+}
+
+void OldStyleLogProvider::Warning(const char *message,
+                                  const char *filename,
+                                  int line,
+                                  const char *function)
+{
+    if (m_showWarning) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", WARNING_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), WARNING_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", WARNING_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), WARNING_END);
+        }
+    }
+}
+
+void OldStyleLogProvider::Error(const char *message,
+                                const char *filename,
+                                int line,
+                                const char *function)
+{
+    if (m_showError) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", ERROR_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), ERROR_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", ERROR_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), ERROR_END);
+        }
+    }
+}
+
+void OldStyleLogProvider::Pedantic(const char *message,
+                                   const char *filename,
+                                   int line,
+                                   const char *function)
+{
+    if (m_showPedantic) {
+        if (m_printStdErr) {
+            fprintf(stderr, "%s%s%s\n", PEDANTIC_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), PEDANTIC_END);
+        } else {
+            fprintf(stdout, "%s%s%s\n", PEDANTIC_BEGIN,
+                    FormatMessage(message, filename, line,
+                        function).c_str(), PEDANTIC_END);
+        }
+    }
+}
+}
+} // namespace DPL
diff --git a/commons/wrt-commons b/commons/wrt-commons
new file mode 100644 (file)
index 0000000..a285a63
--- /dev/null
@@ -0,0 +1,204 @@
+wrt-commons:
+Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/communication_client/include/SecurityCommunicationClient.h b/communication_client/include/SecurityCommunicationClient.h
new file mode 100644 (file)
index 0000000..1c4b4da
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        SecurityCommunicationClient.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This is header of class used by IPC client with implemented templates
+ *
+ */
+
+/*
+ * This class hides implementation of specific communication types
+ * and enables switching between them by #defined macros.
+ *
+ * supported types : DBUS_CONNECTION
+ *
+ * IMPORTANT : Exactly ONE type MUST be defined.
+ *
+ */
+
+#ifndef SECURITYCOMMUNICATIONCLIENT_H_
+#define SECURITYCOMMUNICATIONCLIENT_H_
+
+#ifdef DBUS_CONNECTION
+#include <dpl/dbus/dbus_client.h>
+#endif
+#include <dpl/log/log.h>
+#include "SecuritySocketClient.h"
+#include <string>
+#include <memory>
+
+
+namespace WrtSecurity {
+namespace Communication {
+class Client
+{
+public:
+    class Exception
+    {
+    public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SecurityCommunicationClientException)
+    };
+
+    explicit Client(const std::string &intefaceName);
+
+
+
+    template<typename ... Args>
+    void call(const char* methodName, const Args& ... args)
+    {
+
+        connect();
+        Try{
+        #ifdef DBUS_CONNECTION
+            m_dbusClient->call(methodName, args...);
+        } Catch (DPL::DBus::Client::Exception::DBusClientException){
+        #endif //DBUS_CONNECTION
+        #ifdef SOCKET_CONNECTION
+            m_socketClient->call(methodName, args...);
+        } Catch (SecuritySocketClient::Exception::SecuritySocketClientException){
+        #endif //SOCKET_CONNECTION
+            LogError("Error getting response");
+            disconnect();
+            ReThrowMsg(Exception::SecurityCommunicationClientException,
+                       "Error getting response");
+        }
+        LogInfo("Call served");
+        disconnect();
+  }
+
+    template<typename ...Args>
+    void call(std::string methodName, const Args&... args)
+    {
+        call(methodName.c_str(), args...);
+    }
+
+
+private:
+
+    void connect();
+    void disconnect();
+
+    std::string m_interfaceName;
+    #ifdef DBUS_CONNECTION
+    std::unique_ptr<DPL::DBus::Client> m_dbusClient;
+    #endif
+
+    #ifdef SOCKET_CONNECTION
+    std::unique_ptr<SecuritySocketClient> m_socketClient;
+    #endif
+};
+} // namespace Communication
+} // namespace WrtSecurity
+
+#endif /* SECURITYCOMMUNICATIONCLIENT_H_ */
diff --git a/communication_client/src/SecurityCommunicationClient.cpp b/communication_client/src/SecurityCommunicationClient.cpp
new file mode 100644 (file)
index 0000000..9bc155f
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        SecurityCommunicationClient.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This is implementation of class used IPC client
+ */
+
+
+#include "SecurityCommunicationClient.h"
+
+#ifdef DBUS_CONNECTION
+#include "security_daemon_dbus_config.h"
+#endif
+
+#include <dpl/log/log.h>
+
+namespace WrtSecurity{
+namespace Communication{
+
+  Client::Client(const std::string& interfaceName){
+    #if DBUS_CONNECTION
+      LogInfo("DBus create");
+    Try {
+      m_dbusClient.reset(new DPL::DBus::Client(WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+                         WrtSecurity::SecurityDaemonConfig::SERVICE_NAME(),
+                         interfaceName));
+    } Catch (DPL::DBus::Client::Exception::DBusClientException) {
+      LogError("Error getting connection");
+      ReThrowMsg(Exception::SecurityCommunicationClientException,
+               "Error getting connection");
+    }
+    if(NULL == m_dbusClient.get()){
+      LogError("Couldn't get client");
+      ThrowMsg(Exception::SecurityCommunicationClientException,
+               "Error getting client");
+    }
+    #endif //DBUS_CONNECTION
+
+    #ifdef SOCKET_CONNECTION
+    m_socketClient.reset(new SecuritySocketClient(interfaceName));
+    if(NULL == m_socketClient.get()){
+        LogError("Couldn't get client");
+        ThrowMsg(Exception::SecurityCommunicationClientException,
+                 "Error getting client");
+    }
+    #endif //SOCKET_CONNECTION
+    LogDebug("Created wrt-security communication client");
+  }
+
+  void Client::connect(){
+    #ifdef SOCKET_CONNECTION
+      Try {
+          m_socketClient->connect();
+      } Catch(SecuritySocketClient::Exception::SecuritySocketClientException){
+          LogError("Couldn't connect");
+          ReThrowMsg(Exception::SecurityCommunicationClientException,
+                     "Error connecting");
+      }
+
+    #endif //SOCKET_CONNECTION
+      LogDebug("Wrt-security client Connected");
+  }
+
+  void Client::disconnect(){
+
+    #ifdef SOCKET_CONNECTION
+      m_socketClient->disconnect();
+    #endif //SOCKET_CONNECTION
+      LogDebug("Wrt-security client Disconnected");
+  }
+
+
+} // namespace Communication
+
+} // namespace WrtSecurity
+
diff --git a/etc/CMakeLists.txt b/etc/CMakeLists.txt
new file mode 100644 (file)
index 0000000..ba76f68
--- /dev/null
@@ -0,0 +1,13 @@
+
+SET(ETC_DIR ${PROJECT_SOURCE_DIR}/etc)
+
+  INSTALL(FILES
+    ${ETC_DIR}/wrt_security_create_clean_db.sh
+    ${ETC_DIR}/wrt_security_change_policy.sh
+    DESTINATION /usr/bin
+    )
+
+INSTALL(FILES
+    ${ETC_DIR}/schema.xsd
+    DESTINATION share/wrt-engine
+    )
diff --git a/etc/schema.xsd b/etc/schema.xsd
new file mode 100644 (file)
index 0000000..8028f3e
--- /dev/null
@@ -0,0 +1,415 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE schema
+  PUBLIC "-//W3C//DTD XMLSchema 200102//EN" "http://www.w3.org/2001/XMLSchema.dtd"
+ [
+   <!ATTLIST schema
+     xmlns:ds CDATA #FIXED "http://www.w3.org/2000/09/xmldsig#">
+   <!ENTITY dsig 'http://www.w3.org/2000/09/xmldsig#'>
+   <!ENTITY % p ''>
+   <!ENTITY % s ''>
+  ]>
+
+<!-- Schema for XML Signatures
+    http://www.w3.org/2000/09/xmldsig#
+    $Revision: 1.1 $ on $Date: 2002/02/08 20:32:26 $ by $Author: reagle $
+
+    Copyright 2001 The Internet Society and W3C (Massachusetts Institute
+    of Technology, Institut National de Recherche en Informatique et en
+    Automatique, Keio University). All Rights Reserved.
+    http://www.w3.org/Consortium/Legal/
+
+    This document is governed by the W3C Software License [1] as described
+    in the FAQ [2].
+
+    [1] http://www.w3.org/Consortium/Legal/copyright-software-19980720
+    [2] http://www.w3.org/Consortium/Legal/IPR-FAQ-20000620.html#DTD
+-->
+
+
+<schema xmlns="http://www.w3.org/2001/XMLSchema"
+        xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
+        targetNamespace="http://www.w3.org/2000/09/xmldsig#"
+        version="0.1" elementFormDefault="qualified">
+
+<!-- Basic Types Defined for Signatures -->
+
+<simpleType name="CryptoBinary">
+  <restriction base="base64Binary">
+  </restriction>
+</simpleType>
+
+<!-- Start Signature -->
+
+<element name="Signature" type="ds:SignatureType"/>
+<complexType name="SignatureType">
+  <sequence>
+    <element ref="ds:SignedInfo"/>
+    <element ref="ds:SignatureValue"/>
+    <element ref="ds:KeyInfo" minOccurs="0"/>
+    <element ref="ds:Object" minOccurs="0" maxOccurs="unbounded"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+</complexType>
+
+  <element name="SignatureValue" type="ds:SignatureValueType"/>
+  <complexType name="SignatureValueType">
+    <simpleContent>
+      <extension base="base64Binary">
+        <attribute name="Id" type="ID" use="optional"/>
+      </extension>
+    </simpleContent>
+  </complexType>
+
+<!-- Start SignedInfo -->
+
+<element name="SignedInfo" type="ds:SignedInfoType"/>
+<complexType name="SignedInfoType">
+  <sequence>
+    <element ref="ds:CanonicalizationMethod"/>
+    <element ref="ds:SignatureMethod"/>
+    <element ref="ds:Reference" maxOccurs="unbounded"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+</complexType>
+
+  <element name="CanonicalizationMethod" type="ds:CanonicalizationMethodType"/>
+  <complexType name="CanonicalizationMethodType" mixed="true">
+    <sequence>
+      <any namespace="##any" minOccurs="0" maxOccurs="unbounded"/>
+      <!-- (0,unbounded) elements from (1,1) namespace -->
+    </sequence>
+    <attribute name="Algorithm" type="anyURI" use="required"/>
+  </complexType>
+
+  <element name="SignatureMethod" type="ds:SignatureMethodType"/>
+  <complexType name="SignatureMethodType" mixed="true">
+    <sequence>
+      <element name="HMACOutputLength" minOccurs="0" type="ds:HMACOutputLengthType"/>
+      <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
+      <!-- (0,unbounded) elements from (1,1) external namespace -->
+    </sequence>
+    <attribute name="Algorithm" type="anyURI" use="required"/>
+  </complexType>
+
+<!-- Start Reference -->
+
+<element name="Reference" type="ds:ReferenceType"/>
+<complexType name="ReferenceType">
+  <sequence>
+    <element ref="ds:Transforms" minOccurs="0"/>
+    <element ref="ds:DigestMethod"/>
+    <element ref="ds:DigestValue"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+  <attribute name="URI" type="anyURI" use="optional"/>
+  <attribute name="Type" type="anyURI" use="optional"/>
+</complexType>
+
+  <element name="Transforms" type="ds:TransformsType"/>
+  <complexType name="TransformsType">
+    <sequence>
+      <element ref="ds:Transform" maxOccurs="unbounded"/>
+    </sequence>
+  </complexType>
+
+  <element name="Transform" type="ds:TransformType"/>
+  <complexType name="TransformType" mixed="true">
+    <choice minOccurs="0" maxOccurs="unbounded">
+      <any namespace="##other" processContents="lax"/>
+      <!-- (1,1) elements from (0,unbounded) namespaces -->
+      <element name="XPath" type="string"/>
+    </choice>
+    <attribute name="Algorithm" type="anyURI" use="required"/>
+  </complexType>
+
+<!-- End Reference -->
+
+<element name="DigestMethod" type="ds:DigestMethodType"/>
+<complexType name="DigestMethodType" mixed="true">
+  <sequence>
+    <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
+  </sequence>
+  <attribute name="Algorithm" type="anyURI" use="required"/>
+</complexType>
+
+<element name="DigestValue" type="ds:DigestValueType"/>
+<simpleType name="DigestValueType">
+  <restriction base="base64Binary"/>
+</simpleType>
+
+<!-- End SignedInfo -->
+
+<!-- Start KeyInfo -->
+
+<element name="KeyInfo" type="ds:KeyInfoType"/>
+<complexType name="KeyInfoType" mixed="true">
+  <choice maxOccurs="unbounded">
+    <element ref="ds:KeyName"/>
+    <element ref="ds:KeyValue"/>
+    <element ref="ds:RetrievalMethod"/>
+    <element ref="ds:X509Data"/>
+    <element ref="ds:PGPData"/>
+    <element ref="ds:SPKIData"/>
+    <element ref="ds:MgmtData"/>
+    <any processContents="lax" namespace="##other"/>
+    <!-- (1,1) elements from (0,unbounded) namespaces -->
+  </choice>
+  <attribute name="Id" type="ID" use="optional"/>
+</complexType>
+
+  <element name="KeyName" type="string"/>
+  <element name="MgmtData" type="string"/>
+
+  <element name="KeyValue" type="ds:KeyValueType"/>
+  <complexType name="KeyValueType" mixed="true">
+   <choice>
+     <element ref="ds:DSAKeyValue"/>
+     <element ref="ds:RSAKeyValue"/>
+     <element ref="ds:ECKeyValue"/>
+     <any namespace="##other" processContents="lax"/>
+   </choice>
+  </complexType>
+
+<!-- ECDSA KEY DEFINITIONS -->
+
+  <element name="ECKeyValue" type="ds:ECKeyValueType"/>
+  <complexType name="ECKeyValueType">
+    <sequence>
+      <choice>
+        <element name="ECParameters" type="ds:ECParametersType"/>
+        <element name="NamedCurve" type="ds:NamedCurveType"/>
+      </choice>
+      <element name="PublicKey" type="ds:ECPointType"/>
+    </sequence>
+    <attribute name="Id" type="ID" use="optional"/>
+  </complexType>
+
+  <complexType name="NamedCurveType">
+    <attribute name="URI" type="anyURI" use="required"/>
+  </complexType>
+
+  <simpleType name="ECPointType">
+    <restriction base="ds:CryptoBinary"/>
+  </simpleType>
+
+  <element name="RetrievalMethod" type="ds:RetrievalMethodType"/>
+  <complexType name="RetrievalMethodType">
+    <sequence>
+      <element ref="ds:Transforms" minOccurs="0"/>
+    </sequence>
+    <attribute name="URI" type="anyURI"/>
+    <attribute name="Type" type="anyURI" use="optional"/>
+  </complexType>
+
+    <complexType name="ECParametersType">
+      <sequence>
+        <element name="FieldID" type="ds:FieldIDType"/>
+        <element name="Curve" type="ds:CurveType"/>
+        <element name="Base" type="ds:ECPointType"/>
+        <element name="Order" type="ds:CryptoBinary"/>
+        <element name="CoFactor" type="integer" minOccurs="0"/>
+        <element name="ValidationData" type="ds:ECValidationDataType" minOccurs="0"/>
+      </sequence>
+    </complexType>
+
+    <complexType name="FieldIDType">
+      <choice>
+        <element ref="ds:Prime"/>
+        <element ref="ds:TnB"/>
+        <element ref="ds:PnB"/>
+        <element ref="ds:GnB"/>
+        <any namespace="##other" processContents="lax"/>
+      </choice>
+    </complexType>
+
+    <element name="Prime" type="ds:PrimeFieldParamsType"/>
+    <complexType name="PrimeFieldParamsType">
+      <sequence>
+        <element name="P" type="ds:CryptoBinary"/>
+      </sequence>
+    </complexType>
+
+    <element name="GnB" type="ds:CharTwoFieldParamsType"/>
+    <complexType name="CharTwoFieldParamsType">
+      <sequence>
+        <element name="M" type="positiveInteger"/>
+      </sequence>
+    </complexType>
+
+    <element name="TnB" type="ds:TnBFieldParamsType"/>
+    <complexType name="TnBFieldParamsType">
+      <complexContent>
+        <extension base="ds:CharTwoFieldParamsType">
+          <sequence>
+            <element name="K" type="positiveInteger"/>
+          </sequence>
+        </extension>
+      </complexContent>
+    </complexType>
+
+    <element name="PnB" type="ds:PnBFieldParamsType"/>
+    <complexType name="PnBFieldParamsType">
+      <complexContent>
+        <extension base="ds:CharTwoFieldParamsType">
+          <sequence>
+            <element name="K1" type="positiveInteger"/>
+            <element name="K2" type="positiveInteger"/>
+            <element name="K3" type="positiveInteger"/>
+          </sequence>
+        </extension>
+      </complexContent>
+    </complexType>
+
+    <complexType name="CurveType">
+      <sequence>
+        <element name="A" type="ds:CryptoBinary"/>
+        <element name="B" type="ds:CryptoBinary"/>
+      </sequence>
+    </complexType>
+
+  <complexType name="ECValidationDataType">
+    <sequence>
+      <element name="seed" type="ds:CryptoBinary"/>
+    </sequence>
+    <attribute name="hashAlgorithm" type="anyURI" use="required"/>
+  </complexType>
+
+
+<!-- Start X509Data -->
+
+<element name="X509Data" type="ds:X509DataType"/>
+<complexType name="X509DataType">
+  <sequence maxOccurs="unbounded">
+    <choice>
+      <element name="X509IssuerSerial" type="ds:X509IssuerSerialType"/>
+      <element name="X509SKI" type="base64Binary"/>
+      <element name="X509SubjectName" type="string"/>
+      <element name="X509Certificate" type="base64Binary"/>
+      <element name="X509CRL" type="base64Binary"/>
+      <any namespace="##other" processContents="lax"/>
+    </choice>
+  </sequence>
+</complexType>
+
+<complexType name="X509IssuerSerialType">
+  <sequence>
+    <element name="X509IssuerName" type="string"/>
+    <element name="X509SerialNumber" type="integer"/>
+  </sequence>
+</complexType>
+
+<!-- End X509Data -->
+
+<!-- Begin PGPData -->
+
+<element name="PGPData" type="ds:PGPDataType"/>
+<complexType name="PGPDataType">
+  <choice>
+    <sequence>
+      <element name="PGPKeyID" type="base64Binary"/>
+      <element name="PGPKeyPacket" type="base64Binary" minOccurs="0"/>
+      <any namespace="##other" processContents="lax" minOccurs="0"
+       maxOccurs="unbounded"/>
+    </sequence>
+    <sequence>
+      <element name="PGPKeyPacket" type="base64Binary"/>
+      <any namespace="##other" processContents="lax" minOccurs="0"
+       maxOccurs="unbounded"/>
+    </sequence>
+  </choice>
+</complexType>
+
+<!-- End PGPData -->
+
+<!-- Begin SPKIData -->
+
+<element name="SPKIData" type="ds:SPKIDataType"/>
+<complexType name="SPKIDataType">
+  <sequence maxOccurs="unbounded">
+    <element name="SPKISexp" type="base64Binary"/>
+    <any namespace="##other" processContents="lax" minOccurs="0"/>
+  </sequence>
+</complexType>
+
+<!-- End SPKIData -->
+
+<!-- End KeyInfo -->
+
+<!-- Start Object (Manifest, SignatureProperty) -->
+
+<element name="Object" type="ds:ObjectType"/>
+<complexType name="ObjectType" mixed="true">
+  <sequence minOccurs="0" maxOccurs="unbounded">
+    <any namespace="##any" processContents="lax"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+  <attribute name="MimeType" type="string" use="optional"/> <!-- add a grep facet -->
+  <attribute name="Encoding" type="anyURI" use="optional"/>
+</complexType>
+
+<element name="Manifest" type="ds:ManifestType"/>
+<complexType name="ManifestType">
+  <sequence>
+    <element ref="ds:Reference" maxOccurs="unbounded"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+</complexType>
+
+<element name="SignatureProperties" type="ds:SignaturePropertiesType"/>
+<complexType name="SignaturePropertiesType">
+  <sequence>
+    <element ref="ds:SignatureProperty" maxOccurs="unbounded"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+</complexType>
+
+   <element name="SignatureProperty" type="ds:SignaturePropertyType"/>
+   <complexType name="SignaturePropertyType" mixed="true">
+     <choice maxOccurs="unbounded">
+       <any namespace="##other" processContents="lax"/>
+       <!-- (1,1) elements from (1,unbounded) namespaces -->
+     </choice>
+     <attribute name="Target" type="anyURI" use="required"/>
+     <attribute name="Id" type="ID" use="optional"/>
+   </complexType>
+
+<!-- End Object (Manifest, SignatureProperty) -->
+
+<!-- Start Algorithm Parameters -->
+
+<simpleType name="HMACOutputLengthType">
+  <restriction base="integer"/>
+</simpleType>
+
+<!-- Start KeyValue Element-types -->
+
+<element name="DSAKeyValue" type="ds:DSAKeyValueType"/>
+<complexType name="DSAKeyValueType">
+  <sequence>
+    <sequence minOccurs="0">
+      <element name="P" type="ds:CryptoBinary"/>
+      <element name="Q" type="ds:CryptoBinary"/>
+    </sequence>
+    <element name="G" type="ds:CryptoBinary" minOccurs="0"/>
+    <element name="Y" type="ds:CryptoBinary"/>
+    <element name="J" type="ds:CryptoBinary" minOccurs="0"/>
+    <sequence minOccurs="0">
+      <element name="Seed" type="ds:CryptoBinary"/>
+      <element name="PgenCounter" type="ds:CryptoBinary"/>
+    </sequence>
+  </sequence>
+</complexType>
+
+<element name="RSAKeyValue" type="ds:RSAKeyValueType"/>
+<complexType name="RSAKeyValueType">
+  <sequence>
+    <element name="Modulus" type="ds:CryptoBinary"/>
+    <element name="Exponent" type="ds:CryptoBinary"/>
+  </sequence>
+</complexType>
+
+<!-- End KeyValue Element-types -->
+
+<!-- End Signature -->
+
+</schema>
diff --git a/etc/wrt_security_change_policy.sh b/etc/wrt_security_change_policy.sh
new file mode 100644 (file)
index 0000000..8a65b7e
--- /dev/null
@@ -0,0 +1,26 @@
+#!/bin/sh
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+
+#Uncomment this when IPC is set to DBus
+#dbus-send --system --print-reply --dest=org.tizen.SecurityDaemon /org/tizen/SecurityDaemon org.tizen.AceCheckAccessInterface.update_policy
+
+#Uncomment this when IPC is set to sockets
+echo "delete from AcePolicyResult where 1==1;" | /usr/bin/sqlite3 /opt/dbspace/.ace.db
+echo "delete from AceAttribute where 1==1;" | /usr/bin/sqlite3 /opt/dbspace/.ace.db
+echo "delete from AcePromptDecision where 1==1;" | /usr/bin/sqlite3 /opt/dbspace/.ace.db
+/usr/bin/pkill -9 wrt-security
+/bin/sleep 3
+
diff --git a/etc/wrt_security_create_clean_db.sh b/etc/wrt_security_create_clean_db.sh
new file mode 100644 (file)
index 0000000..08d7a3f
--- /dev/null
@@ -0,0 +1,36 @@
+#!/bin/sh
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+for name in ace
+do
+    rm -f /opt/dbspace/.$name.db
+    rm -f /opt/dbspace/.$name.db-journal
+    SQL="PRAGMA journal_mode = PERSIST;"
+    sqlite3 /opt/dbspace/.$name.db "$SQL"
+    SQL=".read /usr/share/wrt-engine/"$name"_db.sql"
+    sqlite3 /opt/dbspace/.$name.db "$SQL"
+    touch /opt/dbspace/.$name.db-journal
+    chown 0:6026 /opt/dbspace/.$name.db
+    chown 0:6026 /opt/dbspace/.$name.db-journal
+    chmod 660 /opt/dbspace/.$name.db
+    chmod 660 /opt/dbspace/.$name.db-journal
+    if [ -f /usr/lib/rpm-plugins/msm.so ]
+    then
+        chsmack -a "wrt-security-daemon::db" /opt/dbspace/.$name.db
+        chsmack -a "wrt-security-daemon::db" /opt/dbspace/.$name.db-journal
+    fi
+done
+
+
diff --git a/mockups/AceDAOReadOnly_mock.cpp b/mockups/AceDAOReadOnly_mock.cpp
new file mode 100644 (file)
index 0000000..9a463d8
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @author     Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version    0.1
+ * @brief      ACE DAO read only mockup class
+ */
+#include "AceDAOReadOnly_mock.h"
+
+namespace AceDB {
+OptionalExtendedPolicyResult AceDAOReadOnly::m_policyResult = ExtendedPolicyResult();
+OptionalCachedPromptDecision AceDAOReadOnly::m_promptDecision =
+        OptionalCachedPromptDecision();
+PreferenceTypes AceDAOReadOnly::m_devCapSetting =
+        PreferenceTypes::PREFERENCE_DEFAULT;
+PreferenceTypes AceDAOReadOnly::m_widgetDevCapSetting =
+        PreferenceTypes::PREFERENCE_DEFAULT;
+PreferenceTypesMap AceDAOReadOnly::m_devCapSettings = PreferenceTypesMap();
+BaseAttributeSet AceDAOReadOnly::m_attributeSet = BaseAttributeSet();
+BasePermissionList AceDAOReadOnly::m_widgetDevCapSettings = BasePermissionList();
+RequestedDevCapsMap AceDAOReadOnly::m_devCapPermissions =
+        RequestedDevCapsMap();
+FeatureNameVector AceDAOReadOnly::m_featureName;
+std::string AceDAOReadOnly::m_guid = std::string();
+};
diff --git a/mockups/AceDAOReadOnly_mock.h b/mockups/AceDAOReadOnly_mock.h
new file mode 100644 (file)
index 0000000..b28b304
--- /dev/null
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @author     Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version    0.1
+ * @brief      ACE DAO read only mockup class
+ */
+
+#ifndef WRT_MOCKUPS_ACE_DAO_READ_ONLY_MOCK_H_
+#define WRT_MOCKUPS_ACE_DAO_READ_ONLY_MOCK_H_
+
+#include <set>
+#include <utility>
+#include <string>
+
+#include <openssl/md5.h>
+#include <dpl/exception.h>
+#include <dpl/string.h>
+
+#include <PreferenceTypes.h>
+#include <BaseAttribute.h>
+#include <BasePermission.h>
+#include <IRequest.h>
+#include <PolicyEffect.h>
+#include <PolicyResult.h>
+#include <PromptDecision.h>
+#include <dpl/foreach.h>
+
+namespace AceDB {
+
+typedef std::map<DPL::String, bool> RequestedDevCapsMap;
+typedef DPL::String FeatureName;
+typedef std::vector<FeatureName> FeatureNameVector;
+
+class AceDAOReadOnly
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, DatabaseError)
+    };
+
+    AceDAOReadOnly() {}
+
+    static void attachToThreadRO(){};
+    static void attachToThreadRW(){};
+    static void detachFromThread(){};
+
+    // policy effect/decision
+    static OptionalExtendedPolicyResult getPolicyResult(
+            const BaseAttributeSet &/*attributes*/)
+    {
+        return m_policyResult;
+    }
+
+    // prompt decision
+    static OptionalCachedPromptDecision getPromptDecision(
+            WidgetHandle /*widgetHandle*/,
+            int /*hash*/)
+    {
+        return m_promptDecision;
+    }
+
+    // resource settings
+    static PreferenceTypes getDevCapSetting(const std::string &/*resource*/)
+    {
+        return m_devCapSetting;
+    }
+    static void getDevCapSettings(PreferenceTypesMap *preferences)
+    {
+        *preferences = m_devCapSettings;
+    }
+
+    // user settings
+    static void getWidgetDevCapSettings(BasePermissionList *permissions)
+    {
+        *permissions = m_widgetDevCapSettings;
+    }
+
+    static PreferenceTypes getWidgetDevCapSetting(
+            const std::string &/*resource*/,
+            WidgetHandle /*handler*/)
+    {
+        return m_widgetDevCapSetting;
+    }
+
+    static void getAttributes(BaseAttributeSet *attributes)
+    {
+        *attributes = m_attributeSet;
+    }
+
+    static void getRequestedDevCaps(
+        int /*widgetHandle*/,
+        RequestedDevCapsMap *permissions)
+    {
+        *permissions = m_devCapPermissions;
+    }
+
+    // Setting return values for mockups
+    static void setPolicyResult(OptionalExtendedPolicyResult value)
+    {
+        m_policyResult = value;
+    }
+
+    static void setPromptDecision(OptionalCachedPromptDecision value)
+    {
+        m_promptDecision = value;
+    }
+
+    static void setDevCapSetting(PreferenceTypes value)
+    {
+        m_devCapSetting = value;
+    }
+
+    static void setWidgetDevCapSetting(PreferenceTypes value)
+    {
+        m_widgetDevCapSetting = value;
+    }
+
+    static void setWidgetDevCapSettings(BasePermissionList value)
+    {
+        m_widgetDevCapSettings = value;
+    }
+
+    static void setDevCapSettings(PreferenceTypesMap value)
+    {
+        m_devCapSettings = value;
+    }
+
+    static void setAttributeSet(BaseAttributeSet value)
+    {
+        m_attributeSet = value;
+    }
+
+    static void setDevCapPermissions(RequestedDevCapsMap value)
+    {
+        m_devCapPermissions = value;
+    }
+
+    static void getAcceptedFeature(
+        WidgetHandle /* widgetHandle */,
+        FeatureNameVector *featureVector)
+    {
+        *featureVector = m_featureName;
+    }
+
+    static void setAcceptedFeature(const FeatureNameVector &fvector)
+    {
+        m_featureName = fvector;
+    }
+
+    static std::string getGUID(const WidgetHandle& handle)
+    {
+        return m_guid;
+    }
+
+  protected:
+    static OptionalExtendedPolicyResult m_policyResult;
+    static OptionalCachedPromptDecision m_promptDecision;
+    static PreferenceTypes m_devCapSetting;
+    static PreferenceTypes m_widgetDevCapSetting;
+    static PreferenceTypesMap m_devCapSettings;
+    static BaseAttributeSet m_attributeSet;
+    static BasePermissionList m_widgetDevCapSettings;
+    static RequestedDevCapsMap m_devCapPermissions;
+    static FeatureNameVector m_featureName;
+    static std::string m_guid;
+};
+
+}
+
+#endif // WRT_MOCKUPS_ACE_DAO_READ_ONLY_MOCK_H_
diff --git a/mockups/PolicyInformationPoint_mock.h b/mockups/PolicyInformationPoint_mock.h
new file mode 100644 (file)
index 0000000..07ced18
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @author  Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version 1.0
+ * @brief   PolicyInformationPoint mockup class
+ */
+#ifndef WRT_MOCKUPS_POLICY_INFORMATION_POINT_MOCK_H_
+#define WRT_MOCKUPS_POLICY_INFORMATION_POINT_MOCK_H_
+
+class PolicyInformationPoint {
+  public:
+    PolicyInformationPoint(void*, void*, void*){};
+    virtual ~PolicyInformationPoint(){};
+    void getAttributesValues(void*, void*){};
+
+};
+
+#endif // WRT_MOCKUPS_POLICY_INFORMATION_POINT_MOCK_H_
diff --git a/mockups/communication_client_mock.cpp b/mockups/communication_client_mock.cpp
new file mode 100644 (file)
index 0000000..bb75880
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       DBus client mockup class.
+ */
+#include "communication_client_mock.h"
+
+namespace WrtSecurity {
+namespace Communication {
+    int Client::m_checkAccessResult = 0;
+    bool Client::m_validationResult = true;
+}
+};
diff --git a/mockups/communication_client_mock.h b/mockups/communication_client_mock.h
new file mode 100644 (file)
index 0000000..457fd0e
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       DBus client mockup class.
+ */
+
+#ifndef WRT_MOCKUPS_DBUS_CLIENT_MOCK_H_
+#define WRT_MOCKUPS_DBUS_CLIENT_MOCK_H_
+
+#include <dpl/exception.h>
+#include <dpl/assert.h>
+
+#include <string>
+#include <vector>
+#include "ace_server_api.h"
+#include "popup_response_server_api.h"
+
+namespace WrtSecurity {
+namespace Communication {
+
+/*
+ * This class is a mockup implementation for some methods called
+ * with DBus::Client.
+ */
+
+class Client
+{
+
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SecurityCommunicationClientException)
+    };
+
+    Client(std::string /*interfaceName*/)
+    {
+    }
+
+    // ACE server api check access method
+    void call(const std::string &methodName,
+              int,
+              const std::string&,
+              const std::string&,
+              const std::vector<std::string>&,
+              const std::vector<std::string>&,
+              const std::string&,
+              int* outArg)
+    {
+        if (methodName == WrtSecurity::AceServerApi::CHECK_ACCESS_METHOD()) {
+            Assert(NULL != outArg);
+            *outArg = m_checkAccessResult;
+            return;
+        }
+    }
+
+    void call(const std::string &methodName,
+                  bool,
+                  int,
+                  int,
+                  const std::string&,
+                  const std::string&,
+                  const std::vector<std::string>&,
+                  const std::vector<std::string>&,
+                  const std::string&,
+                  bool* outArg)
+    {
+        if (methodName == WrtSecurity::PopupServerApi::VALIDATION_METHOD()) {
+            Assert(NULL != outArg);
+            *outArg = m_validationResult;
+            return;
+        }
+    }
+
+
+    ~Client()
+    {
+    }
+
+    static void setCheckAccessResult(int value)
+    {
+        m_checkAccessResult = value;
+    }
+
+    static void setValidationResult(bool value)
+    {
+        m_validationResult = value;
+    }
+
+  private:
+    static int m_checkAccessResult;
+    static bool m_validationResult;
+};
+
+} // namespace DBus
+}
+
+#endif // WRT_MOCKUPS_DBUS_CLIENT_MOCK_H_
diff --git a/packaging/wrt-security.changes b/packaging/wrt-security.changes
new file mode 100644 (file)
index 0000000..893d2eb
--- /dev/null
@@ -0,0 +1,12 @@
+* Thu Sep 12 2013 Hyunwoo Kim <hwlove.kim@samsung.com>
+- Use GDbus instead of dbus-glib
+- Start ecore main loop in main()
+- Add API for removing requested device capabilities of widget
+
+* Tue Aug 20 2013 Hyunwoo Kim <hwlove.kim@samsung.com>
+- Remove ace_check_access and Add ace_check_access_ex.
+- Remove roaming attribute.
+* Mon Aug 5 2013 Hyunwoo Kim <hwlove.kim@samsung.com>
+- Add ace checking API that can return reason of access denial(Privilge or Privacy)
+* Thu Jul 25 2013 Hyunwoo Kim <hwlove.kim@samsung.com>
+- Remove unused logs
diff --git a/packaging/wrt-security.manifest b/packaging/wrt-security.manifest
new file mode 100644 (file)
index 0000000..a61f2e7
--- /dev/null
@@ -0,0 +1,20 @@
+<manifest>
+       <define>
+               <domain name="wrt-security-daemon" />
+               <provide>
+                       <label name="wrt-security-daemon::daemon" />
+                       <label name="wrt-security-daemon::db" />
+               </provide>
+       </define>
+       <request>
+               <domain name="_" />
+       </request>
+       <assign>
+               <filesystem path="/usr/bin/wrt_security_change_policy.sh" exec_label="none"/>
+               <filesystem path="/usr/bin/wrt-security-daemon" label="wrt-security-daemon" exec_label="wrt-security-daemon"/>
+               <filesystem path="/usr/lib/systemd/system/wrt-security-daemon.service" label="_" exec_label="none" />
+               <filesystem path="/usr/lib/systemd/system/wrt-security-daemon.socket" label="_" exec_label="none" />
+               <filesystem path="/usr/lib/systemd/system/multi-user.target.wants/wrt-security-daemon.service" label="_" exec_label="none" />
+               <filesystem path="/usr/lib/systemd/system/sockets.target.wants/wrt-security-daemon.socket" label="_" exec_label="none" />
+       </assign>
+</manifest>
diff --git a/packaging/wrt-security.spec b/packaging/wrt-security.spec
new file mode 100644 (file)
index 0000000..3020e08
--- /dev/null
@@ -0,0 +1,197 @@
+Name:       wrt-security
+Summary:    Wrt security daemon.
+Version:    0.0.67
+Release:    0
+Group:      Security/Access Control
+License:    Apache License, Version 2.0
+URL:        N/A
+Source0:    %{name}-%{version}.tar.gz
+Source1001: %{name}.manifest
+BuildRequires: cmake
+BuildRequires: zip
+BuildRequires: pkgconfig(dlog)
+BuildRequires: pkgconfig(openssl)
+BuildRequires: libattr-devel
+BuildRequires: pkgconfig(libsmack)
+BuildRequires: pkgconfig(dbus-1)
+BuildRequires: pkgconfig(libpcrecpp)
+BuildRequires: pkgconfig(icu-i18n)
+BuildRequires: pkgconfig(libsoup-2.4)
+BuildRequires: pkgconfig(xmlsec1)
+BuildRequires: pkgconfig(capi-appfw-app-manager)
+BuildRequires: pkgconfig(capi-appfw-package-manager)
+BuildRequires: pkgconfig(privacy-manager-client)
+BuildRequires: pkgconfig(privacy-manager-server)
+BuildRequires: pkgconfig(dpl-wrt-dao-ro)
+BuildRequires: pkgconfig(libsystemd-daemon)
+BuildRequires: pkgconfig(sqlite3)
+BuildRequires: pkgconfig(db-util)
+
+BuildRequires: tizen-security-policy
+Requires: tizen-security-policy
+%{?systemd_requires}
+
+%description
+Wrt security daemon and utilities.
+
+%package -n wrt-security-devel
+Summary:    Header files for client libraries.
+Group:      Development/Libraries
+Requires:   wrt-security = %{version}-%{release}
+
+%description -n wrt-security-devel
+Developer files for client libraries.
+
+#%package -n wrt-security-tests
+#Summary: test for wrt-security
+#Group: Development
+#Requires: wrt-security = %{version}-%{release}
+
+#%description -n wrt-security-tests
+#Tests for wrt security.
+
+%define enable_privacy_manager 1
+%define enable_wrt_ocsp 0
+
+%prep
+%setup -q
+cp %{SOURCE1001} .
+
+%build
+export LDFLAGS+="-Wl,--rpath=%{_libdir}"
+
+%cmake . -DDPL_LOG="ON" \
+        -DVERSION=%{version} \
+        -DCMAKE_BUILD_TYPE=%{?build_type:%build_type} \
+%if 0%{?enable_wrt_ocsp}
+        -DENABLE_WRT_OCSP=1 \
+%else
+        -DENABLE_WRT_OCSP=0 \
+%endif
+%if 0%{?enable_privacy_manager}
+       -DENABLE_PRIVACY_MANAGER=1 
+%endif
+
+
+make %{?jobs:-j%jobs}
+
+
+%install
+rm -rf %{buildroot}
+mkdir -p %{buildroot}/usr/share/license
+cp LICENSE %{buildroot}/usr/share/license/%{name}
+
+%make_install
+mkdir -p %{buildroot}%{_libdir}/systemd/system/multi-user.target.wants
+mkdir -p %{buildroot}%{_libdir}/systemd/system/sockets.target.wants
+ln -sf /usr/lib/systemd/system/wrt-security-daemon.service %{buildroot}%{_libdir}/systemd/system/multi-user.target.wants/wrt-security-daemon.service
+ln -sf /usr/lib/systemd/system/wrt-security-daemon.socket  %{buildroot}%{_libdir}/systemd/system/sockets.target.wants/wrt-security-daemon.socket
+
+%clean
+rm -rf %{buildroot}
+
+%post
+if [ ! -e "/opt/dbspace/.ace.db" ]; then
+    echo "This is new install of wrt-security"
+    echo "Calling /usr/bin/wrt_security_create_clean_db.sh"
+    /usr/bin/wrt_security_create_clean_db.sh
+else
+    # Find out old and new version of databases
+    ACE_OLD_DB_VERSION=`sqlite3 /opt/dbspace/.ace.db ".tables" | grep "DB_VERSION_"`
+    ACE_NEW_DB_VERSION=`cat /usr/share/wrt-engine/ace_db.sql | tr '[:blank:]' '\n' | grep DB_VERSION_`
+    echo "OLD ace database version ${ACE_OLD_DB_VERSION}"
+    echo "NEW ace database version ${ACE_NEW_DB_VERSION}"
+
+    if [ ${ACE_OLD_DB_VERSION} -a ${ACE_NEW_DB_VERSION} ]
+    then
+        if [ ${ACE_NEW_DB_VERSION} = ${ACE_OLD_DB_VERSION} ]
+        then
+            echo "Equal database detected so db installation ignored"
+        else
+            echo "Calling /usr/bin/wrt_security_create_clean_db.sh"
+            /usr/bin/wrt_security_create_clean_db.sh
+        fi
+    else
+        echo "Calling /usr/bin/wrt_security_create_clean_db.sh"
+        /usr/bin/wrt_security_create_clean_db.sh
+    fi
+fi
+
+/sbin/ldconfig
+echo "[WRT] wrt-security postinst done ..."
+
+%postun
+/sbin/ldconfig
+
+%files -n wrt-security
+%manifest %{name}.manifest
+%defattr(-,root,root,-)
+%attr(755,root,root) /usr/bin/wrt-security-daemon
+%{_libdir}/libace*.so
+%{_libdir}/libace*.so.*
+%{_libdir}/libwrt-security-commons.so
+%{_libdir}/libwrt-security-commons.so.*
+%{_libdir}/libwrt-security-commons-log.so
+%{_libdir}/libwrt-security-commons-log.so.*
+%{_libdir}/libwrt-security-commons-db.so
+%{_libdir}/libwrt-security-commons-db.so.*
+%if 0%{?enable_wrt_ocsp}
+%{_libdir}/libwrt-ocsp.so
+%{_libdir}/libwrt-ocsp.so.*
+%endif
+
+/usr/share/wrt-engine/*
+%attr(755,root,root) %{_bindir}/wrt_security_create_clean_db.sh
+%attr(755,root,root) %{_bindir}/wrt_security_change_policy.sh
+%attr(664,root,root) %{_datadir}/dbus-1/services/*
+%attr(664,root,root) /usr/etc/ace/bondixml*
+%attr(664,root,root) /usr/etc/ace/UnrestrictedPolicy.xml
+%attr(664,root,root) /usr/etc/ace/WAC2.0Policy.xml
+%{_datadir}/license/%{name}
+%{_libdir}/systemd/*
+
+%files -n wrt-security-devel
+%manifest %{name}.manifest
+%defattr(-,root,root,-)
+%{_includedir}/wrt-security/*
+%{_includedir}/ace/*
+%{_includedir}/ace-client/*
+%{_includedir}/ace-settings/*
+%{_includedir}/ace-install/*
+%{_includedir}/ace-common/*
+%{_includedir}/ace-popup-validation/*
+%{_libdir}/pkgconfig/security-client.pc
+%{_libdir}/pkgconfig/security-communication-client.pc
+%{_libdir}/pkgconfig/security-core.pc
+%{_libdir}/pkgconfig/security-dao-ro.pc
+%{_libdir}/pkgconfig/security-dao-rw.pc
+%{_libdir}/pkgconfig/security-install.pc
+%{_libdir}/pkgconfig/security-popup-validation.pc
+%{_libdir}/pkgconfig/security-settings.pc
+%{_libdir}/pkgconfig/security.pc
+%{_libdir}/pkgconfig/wrt-security-commons.pc
+%{_libdir}/pkgconfig/wrt-security-commons-log.pc
+%{_libdir}/pkgconfig/wrt-security-commons-db.pc
+%if 0%{?enable_wrt_ocsp}
+%{_includedir}/wrt-ocsp/*
+%{_libdir}/pkgconfig/security-wrt-ocsp.pc
+%endif
+
+#%files -n wrt-security-tests
+#/usr/bin/wrt-test*
+#/usr/bin/security-tests*
+#/usr/etc/ace/policy*
+#/usr/etc/ace/attr*
+#/usr/etc/ace/general*
+#/usr/etc/ace/inter*
+#/usr/etc/ace/undefined*
+#/usr/etc/ace/CMTest/*
+#/usr/etc/ace/TizenPolicy-test.xml
+#/usr/etc/ace/WAC2.0Policy-test.xml
+#/opt/share/cert-svc/certs/code-signing/wac/root_cacert.pem
+#/usr/etc/ace/ipc-tests-demo.xml
+#/usr/etc/ace/ace-install-api-demo-policy.xml
+#/usr/etc/ace/GeolocationPolicyTest*
+#/opt/apps/widget/tests/geolocation/geolocationSecurityTest*
+#/opt/apps/widget/tests/smack/smacksecurity*
+#/usr/etc/ace/PermitAllPolicy.xml
diff --git a/socket_connection/client/SecuritySocketClient.cpp b/socket_connection/client/SecuritySocketClient.cpp
new file mode 100644 (file)
index 0000000..7d5d0c5
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        SecuritySocketClient.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implemtation of socket client class.
+ */
+
+#include <sys/socket.h>
+#include <string.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/un.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "SecuritySocketClient.h"
+#include "security_daemon_socket_config.h"
+
+void SecuritySocketClient::throwWithErrnoMessage(const std::string& specificInfo){
+    LogError(specificInfo << " : " << strerror(errno));
+    ThrowMsg(Exception::SecuritySocketClientException, specificInfo << " : " << strerror(errno));
+}
+
+SecuritySocketClient::SecuritySocketClient(const std::string& interfaceName) {
+    m_interfaceName = interfaceName;
+    m_serverAddress = WrtSecurity::SecurityDaemonSocketConfig::SERVER_ADDRESS();
+#ifdef ALL_LOGS
+    LogDebug("Client created");
+#endif
+}
+
+void SecuritySocketClient::connect(){
+    struct sockaddr_un remote;
+    if(-1 == (m_socketFd = socket(AF_UNIX, SOCK_STREAM,0))){
+       LogError("SecuritySocketClient: socket creation of wrt-security client socket failed." << errno);
+        throwWithErrnoMessage("socket()");
+    }
+
+    //socket needs to be nonblocking, because read can block after select
+    int flags;
+    if (-1 == (flags = fcntl(m_socketFd, F_GETFL, 0)))
+        flags = 0;
+    if(-1 == (fcntl(m_socketFd, F_SETFL, flags | O_NONBLOCK))){
+       LogError("SecuritySocketClient: fcntl on wrt-security client socket failed." << errno);
+        throwWithErrnoMessage("fcntl");
+    }
+
+    bzero(&remote, sizeof(remote));
+    remote.sun_family = AF_UNIX;
+    strncpy(remote.sun_path, m_serverAddress.c_str(), sizeof(remote.sun_path) - 1);
+    if(-1 == ::connect(m_socketFd, (struct sockaddr *)&remote, SUN_LEN(&remote))){
+       LogError("SecuritySocketClient: Connection with wrt-security failed." << errno);
+        throwWithErrnoMessage("connect()");
+    }
+
+    m_socketConnector.reset(new SocketConnection(m_socketFd));
+
+    LogDebug("Client connected");
+}
+
+void SecuritySocketClient::disconnect(){
+    //Socket should be already closed by server side, 
+    //even though we should close it in case of any errors
+    close(m_socketFd);
+    LogDebug("Client disconnected");
+}
diff --git a/socket_connection/client/SecuritySocketClient.h b/socket_connection/client/SecuritySocketClient.h
new file mode 100644 (file)
index 0000000..7d4bc95
--- /dev/null
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        SecuritySocketClient.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of socket client class.
+ */
+
+#ifndef SECURITYSOCKETCLIENT_H_
+#define SECURITYSOCKETCLIENT_H_
+
+#include <memory>
+#include <string>
+#include <dpl/log/log.h>
+#include "SocketConnection.h"
+
+/* IMPORTANT:
+ * Methods connect(), call() and disconnected() should be called one by one.
+ * Between connect() and disconnect() you can use call() only once.
+ * It is because of timeout on call, e.g. to avoid waiting for corrupted data.
+ */
+
+/* USAGE:
+ * Class should be used according to this scheme:
+ * SecuritySocketClient client("Interface Name");
+ * (...)
+ * client.connect();
+ * client.call("Method name", in_arg1, in_arg2, ..., in_argN,
+ *             out_arg1, out_arg2, ..., out_argM);
+ * client.disconnect();
+ * (...)
+ *
+ * input parameters of the call are passed with reference,
+ * output ones are passed as pointers - parameters MUST be passed this way.
+ *
+ * Currently client supports serialization and deserialization of simple types
+ * (int, char, float, unsigned), strings (std::string and char*) and
+ * some STL containers (std::vector, std::list, std::map, std::pair).
+ * Structures and classes are not (yet) supported.
+ */
+
+class SecuritySocketClient {
+public:
+    class Exception
+    {
+    public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SecuritySocketClientException)
+    };
+
+    SecuritySocketClient(const std::string &interfaceName);
+    void connect();
+    void disconnect();
+
+    void call(std::string methodName){
+        make_call(m_interfaceName);
+        make_call(methodName);
+    }
+
+    template<typename ...Args>
+    void call(std::string methodName, const Args&... args){
+        make_call(m_interfaceName);
+        make_call(methodName);
+        make_call(args...);
+    }
+
+private:
+    template<typename T, typename ...Args>
+    void make_call(const T& invalue, const Args&... args){
+        make_call(invalue);
+        make_call(args...);
+    }
+
+    template<typename T>
+    void make_call(const T& invalue){
+        Try {
+            m_socketConnector->write(invalue);
+        }
+        Catch (SocketConnection::Exception::SocketConnectionException){
+            LogError("Socket connection write error");
+            ReThrowMsg(Exception::SecuritySocketClientException,"Socket connection write error");
+        }
+    }
+
+    template<typename T, typename ...Args>
+    void make_call(const T* invalue, const Args&... args){
+        make_call(invalue);
+        make_call(args...);
+    }
+
+    template<typename T>
+    void make_call(const T* invalue){
+        Try {
+            m_socketConnector->write(invalue);
+        }
+        Catch (SocketConnection::Exception::SocketConnectionException){
+            LogError("Socket connection write error");
+            ReThrowMsg(Exception::SecuritySocketClientException,"Socket connection write error");
+        }
+    }
+
+    template<typename T, typename ...Args>
+    void make_call(T * outvalue, const Args&... args){
+        make_call(outvalue);
+        make_call(args...);
+    }
+
+    template<typename T>
+    void make_call(T* outvalue){
+        Try {
+            m_socketConnector->read(outvalue);
+        }
+        Catch (SocketConnection::Exception::SocketConnectionException){
+            LogError("Socket connection read error");
+            ReThrowMsg(Exception::SecuritySocketClientException,"Socket connection read error");
+        }
+    }
+
+
+private:
+    void throwWithErrnoMessage(const std::string& specificInfo);
+    std::string m_serverAddress;
+    std::string m_interfaceName;
+    std::unique_ptr<SocketConnection> m_socketConnector;
+    int m_socketFd;
+};
+
+#endif /* SECURITYSOCKETCLIENT_H_ */
diff --git a/socket_connection/connection/SocketConnection.cpp b/socket_connection/connection/SocketConnection.cpp
new file mode 100644 (file)
index 0000000..f504bae
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        SocketConnection.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ */
+
+#include "SocketConnection.h"
+
+//
+// Note:
+//
+// The file here is left blank to enable precompilation
+// of templates in corresponding header file.
+// Do not remove this file.
+//
diff --git a/socket_connection/connection/SocketConnection.h b/socket_connection/connection/SocketConnection.h
new file mode 100644 (file)
index 0000000..a11b588
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        SocketConnection.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This file is a header of Socket Connection class with implemented templates
+ */
+
+#ifndef SOCKETCONNECTION_H_
+#define SOCKETCONNECTION_H_
+
+#include <dpl/serialization.h>
+#include <dpl/log/log.h>
+#include <new>
+#include "SocketStream.h"
+
+/*
+ * This class implements interface for generic read and write from given socket.
+ * It does not maintain socket descriptor, so any connecting and disconnecting should be
+ * done above calls to this class.
+ */
+
+/*
+ * Throws SocketConnectionException when read/write will not succeed or if any bad allocation
+ * exception occurs during read.
+ */
+
+class SocketConnection {
+
+public:
+
+    class Exception
+    {
+    public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SocketConnectionException)
+    };
+
+    explicit SocketConnection(int socket_fd) : m_socketStream(socket_fd){
+        LogInfo("Created");
+    }
+
+    template<typename T, typename ...Args>
+    void read(T* out, const Args&... args ){
+        read(out);
+        read(args...);
+    }
+
+    template<typename T>
+    void read(T* out){
+        Try {
+            DPL::Deserialization::Deserialize(m_socketStream, *out);
+        }
+
+        Catch (std::bad_alloc){
+            LogError("Bad allocation error");
+            ThrowMsg(Exception::SocketConnectionException, "Bad allocation error");
+        }
+
+        Catch (SocketStream::Exception::SocketStreamException) {
+            LogError("Socket stream error");
+            ReThrowMsg(Exception::SocketConnectionException, "Socket stream error");
+        }
+    }
+
+    template<typename T, typename ...Args>
+    void write(const T& in, const Args&... args){
+        write(in);
+        write(args...);
+    }
+
+    template<typename T>
+    void write(const T& in){
+        Try {
+            DPL::Serialization::Serialize(m_socketStream, in);
+        } Catch (SocketStream::Exception::SocketStreamException) {
+            LogError("Socket stream error");
+            ReThrowMsg(Exception::SocketConnectionException, "Socket stream error");
+        }
+    }
+
+    template<typename T, typename ...Args>
+    void write(const T* in, const Args&... args){
+        write(in);
+        write(args...);
+    }
+
+    template<typename T>
+        void write(const T* in){
+            Try {
+                DPL::Serialization::Serialize(m_socketStream, in);
+            } Catch (SocketStream::Exception::SocketStreamException) {
+                LogError("Socket stream error");
+                ReThrowMsg(Exception::SocketConnectionException, "Socket stream error");
+            }
+        }
+
+private:
+    SocketStream m_socketStream;
+};
+
+#endif /* SOCKETCONNECTION_H_ */
diff --git a/socket_connection/connection/SocketStream.cpp b/socket_connection/connection/SocketStream.cpp
new file mode 100644 (file)
index 0000000..5ce7666
--- /dev/null
@@ -0,0 +1,171 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        SocketStream.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of socket stream class
+ */
+
+
+#include <sys/socket.h>
+#include <sys/select.h>
+#include <errno.h>
+#include <cstring>
+#include <unistd.h>
+#include <dpl/log/log.h>
+#include "SocketStream.h"
+
+#define READ_TIEMOUT_SEC 1
+#define READ_TIMEUOT_NSEC 0
+#define WRITE_TIMEOUT_SEC 0
+#define WRITE_TIMEOUT_NSEC 100000000
+#define MAX_BUFFER 10240
+
+void SocketStream::throwWithErrnoMessage(std::string function_name){
+    LogError(function_name << " : " << strerror(errno));
+    ThrowMsg(Exception::SocketStreamException, function_name << " : " << strerror(errno));
+}
+
+void SocketStream::Read(size_t num, void * bytes){
+
+    if(NULL == bytes){
+        LogError("Null pointer to buffer");
+        ThrowMsg(Exception::SocketStreamException, "Null pointer to buffer");
+    }
+    
+    m_bytesRead += num;
+    
+    if(m_bytesRead > MAX_BUFFER){
+        LogError("Too big buffer requested!");
+        ThrowMsg(Exception::SocketStreamException, "Too big buffer requested!");
+    }
+
+    char part_buffer[MAX_BUFFER];
+    std::string whole_buffer;
+
+    fd_set rset, allset;
+    int max_fd;
+    ssize_t bytes_read = 0, bytes_to_read = (ssize_t) num;
+
+    timespec timeout;
+
+    max_fd = m_socketFd;
+    ++max_fd;
+
+    FD_ZERO(&allset);
+    FD_SET(m_socketFd, &allset);
+
+    int returned_value;
+
+    while(bytes_to_read != 0){
+        timeout.tv_sec = READ_TIEMOUT_SEC;
+        timeout.tv_nsec = READ_TIMEUOT_NSEC;
+        rset = allset;
+
+        if(-1 == (returned_value = pselect(max_fd, &rset, NULL, NULL, &timeout, NULL))){
+            if(errno == EINTR)
+                continue;
+            else{
+                LogInfo("pselect() : " << strerror(errno));
+            throwWithErrnoMessage("pselect()");
+            }
+        }
+        if(0 == returned_value){
+            //This means pselect got timedout
+            //This is not a proper behavior in reading data from UDS
+            //And could mean we got corrupted connection
+            LogError("Couldn't read whole data. continue..");
+            continue;
+        }
+        if(FD_ISSET(m_socketFd, &rset)){
+            bytes_read = read(m_socketFd, part_buffer, num);
+            if(bytes_read <= 0){
+                if(errno == ECONNRESET || errno == ENOTCONN || errno == ETIMEDOUT){
+                    LogInfo("Connection closed : " << strerror(errno));
+                    ThrowMsg(Exception::SocketStreamException,
+                            "Connection closed : " << strerror(errno) << ". Couldn't read whole data");
+                }else if (errno != EAGAIN && errno != EWOULDBLOCK){
+                    throwWithErrnoMessage("read()");
+                }
+            }
+
+            whole_buffer.append(part_buffer, bytes_read);
+            bytes_to_read-=bytes_read;
+            bytes_read = 0;
+            continue;
+        }
+
+    }
+    memcpy(bytes, whole_buffer.c_str(), num);
+}
+
+void SocketStream::Write(size_t num, const void * bytes){
+
+    if(NULL == bytes){
+        LogError("Null pointer to buffer");
+        ThrowMsg(Exception::SocketStreamException, "Null pointer to buffer");
+    }
+    
+    m_bytesWrote += num;
+    
+    if(m_bytesWrote > MAX_BUFFER){
+        LogError("Too big buffer requested!");
+        ThrowMsg(Exception::SocketStreamException, "Too big buffer requested!");
+    }
+
+    fd_set wset, allset;
+    int max_fd;
+
+    timespec timeout;
+
+    max_fd = m_socketFd;
+    ++max_fd;
+
+    FD_ZERO(&allset);
+    FD_SET(m_socketFd, &allset);
+
+    int returned_value;
+
+    int write_res, bytes_to_write = num;
+    unsigned int current_offset = 0;
+
+    while(current_offset != num){
+        timeout.tv_sec = WRITE_TIMEOUT_SEC;
+        timeout.tv_nsec = WRITE_TIMEOUT_NSEC;
+        wset = allset;
+
+        if(-1 == (returned_value = pselect(max_fd, NULL, &wset, NULL, &timeout, NULL))){
+            if(errno == EINTR) continue;
+            throwWithErrnoMessage("pselect()");
+        }
+
+        if(FD_ISSET(m_socketFd, &wset)){
+            if(-1 == (write_res = write(m_socketFd, reinterpret_cast<const char *>(bytes) + current_offset, bytes_to_write))){
+                if(errno == ECONNRESET || errno == EPIPE){
+                    LogInfo("Connection closed : " << strerror(errno));
+                    ThrowMsg(Exception::SocketStreamException,
+                            "Connection closed : " << strerror(errno) << ". Couldn't write whole data");
+
+                }else if(errno != EAGAIN && errno != EWOULDBLOCK){
+                    throwWithErrnoMessage("write()");
+                }
+            }
+            current_offset += write_res;
+            bytes_to_write -= write_res;
+        }
+    }
+}
diff --git a/socket_connection/connection/SocketStream.h b/socket_connection/connection/SocketStream.h
new file mode 100644 (file)
index 0000000..dc1db61
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        SocketStream.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of socket stream class.
+ */
+
+#ifndef SOCKETSTREAM_H_
+#define SOCKETSTREAM_H_
+
+#include <string>
+#include <sys/socket.h>
+#include <sys/select.h>
+#include <dpl/serialization.h>
+#include <dpl/log/log.h>
+
+/*
+ * This class implements binary read/write from socket used for DPL serialization and deserialization
+ * It can read or write buffers of max *total* size 10kB.
+ * I does not maintain socket descriptor.
+ */
+
+/*
+ * Throws SocketStreamException when buffer is null or its size exceeds max size or when
+ * there is an error during read or write.
+ */
+
+
+
+class SocketStream : public DPL::IStream {
+public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SocketStreamException)
+    };
+
+    explicit SocketStream(int socket_fd) : m_socketFd(socket_fd), 
+                                           m_bytesRead(0),
+                                           m_bytesWrote(0)
+    {
+        LogInfo("Created");
+    }
+    void Read(size_t num, void * bytes);
+    void Write(size_t num, const void * bytes);
+private:
+    void throwWithErrnoMessage(std::string specificInfo);
+    int m_socketFd;
+    int m_bytesRead;
+    int m_bytesWrote;
+};
+
+#endif /* SOCKETSTREAM_H_ */
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..18d0ee7
--- /dev/null
@@ -0,0 +1,166 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+#
+# @file     CMakeLists.txt
+# @author   Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+#
+
+SET(DAEMON_BASIC_DEP
+    dpl-efl
+    dpl-dbus-efl
+    dpl-utils-efl
+    libsoup-2.4
+    openssl
+    libsmack
+    privacy-manager-server
+  )
+
+IF(SMACK_ENABLE)
+    LIST(APPEND DAEMON_BASIC_DEP libprivilege-control)
+ENDIF(SMACK_ENABLE)
+
+IF(NOT DEFINED ENABLE_PRIVACY_MANAGER)
+PKG_CHECK_MODULES(DAEMON_DEP
+    ${DAEMON_BASIC_DEP}
+    REQUIRED
+    libsystemd-daemon)
+ELSE()
+PKG_CHECK_MODULES(DAEMON_DEP
+    ${DAEMON_BASIC_DEP}
+    ${PRIVILEGE_MANAGER_DEP}
+    REQUIRED
+    libsystemd-daemon)
+ENDIF()
+
+SET(DAEMON_SOURCES_PATH ${PROJECT_SOURCE_DIR}/src)
+
+SET(DAEMON_SOURCES
+    #socket connection
+    ${PROJECT_SOURCE_DIR}/socket_connection/connection/SocketConnection.cpp
+    ${PROJECT_SOURCE_DIR}/socket_connection/connection/SocketStream.cpp
+    #caller
+    ${DAEMON_SOURCES_PATH}/services/caller/security_caller.cpp
+    #daemon
+    ${DAEMON_SOURCES_PATH}/daemon/dbus/security_dbus_service.cpp
+    ${DAEMON_SOURCES_PATH}/daemon/sockets/security_socket_service.cpp
+    ${DAEMON_SOURCES_PATH}/daemon/security_daemon.cpp
+    ${DAEMON_SOURCES_PATH}/main.cpp
+    #ocsp
+    ${DAEMON_SOURCES_PATH}/services/ocsp/dbus/ocsp_server_dbus_interface.cpp
+    ${DAEMON_SOURCES_PATH}/services/ocsp/socket/ocsp_service_callbacks.cpp
+    ${DAEMON_SOURCES_PATH}/services/ocsp/ocsp_service.cpp
+    #ace
+    ${DAEMON_SOURCES_PATH}/services/ace/dbus/ace_server_dbus_interface.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/socket/ace_service_callbacks.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/ace_service.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/logic/security_controller.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/logic/attribute_facade.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/logic/security_logic.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/logic/simple_roaming_agent.cpp
+    #popup
+    ${DAEMON_SOURCES_PATH}/services/popup/dbus/popup_response_dbus_interface.cpp
+    ${DAEMON_SOURCES_PATH}/services/popup/socket/popup_service_callbacks.cpp
+  )
+
+SET_SOURCE_FILES_PROPERTIES(${DAEMON_SOURCES} PROPERTIES COMPILE_FLAGS "-std=c++0x")
+
+############################# Lets start compilation process ##################
+
+IF(DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/caller)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/dbus)
+ENDIF()
+
+#ace library
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/ace/include)
+#socket connection library
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/socket_connection/connection)
+#daemon
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/sockets/api)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/sockets)
+#caller
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/caller)
+#ace
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/socket)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/socket/api)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/logic)
+#ocsp
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/socket)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/socket/api)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/logic)
+#popup
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/socket)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/socket/api)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/logic)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/ace/include)
+INCLUDE_DIRECTORIES(${DAEMON_DEP_INCLUDE_DIRS})
+
+IF(NOT DEFINED DBUS_CONNECTION)
+#commons
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    )
+ENDIF()
+
+ADD_EXECUTABLE(${TARGET_DAEMON}
+    ${DAEMON_SOURCES})
+
+IF(DEFINED DBUS_CONNECTION)
+TARGET_LINK_LIBRARIES(${TARGET_DAEMON}
+    ${DAEMON_DEP_LIBRARIES}
+    ${TARGET_ACE_LIB}
+    ${TARGET_ACE_DAO_RW_LIB}
+    )
+ELSE()
+TARGET_LINK_LIBRARIES(${TARGET_DAEMON}
+    ${DAEMON_DEP_LIBRARIES}
+    ${TARGET_ACE_LIB}
+    ${TARGET_ACE_DAO_RW_LIB}
+    libwrt-security-commons
+    libwrt-security-commons-log
+    )
+ENDIF()
+
+INSTALL(TARGETS ${TARGET_DAEMON}
+    DESTINATION bin)
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus/org.tizen.SecurityDaemon.service
+    DESTINATION /usr/share/dbus-1/services
+    )
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/src/services/ace/ace_server_api.h
+    ${PROJECT_SOURCE_DIR}/src/services/ocsp/ocsp_server_api.h
+    ${PROJECT_SOURCE_DIR}/src/services/popup/popup_response_server_api.h
+    ${PROJECT_SOURCE_DIR}/src/services/popup/popup_ace_data_types.h
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus/security_daemon_dbus_config.h
+    DESTINATION /usr/include/wrt-security
+    )
diff --git a/src/TODO.txt b/src/TODO.txt
new file mode 100644 (file)
index 0000000..48755fd
--- /dev/null
@@ -0,0 +1,11 @@
+Security Daemon todos:
+
+* One runtime instance should be allowed (DONE)
+* Hide application symbols that should not be exported.
+* Add support for service/module dependencies.
+* Signals blocking/handlers should be added.
+* Connections to other databases should be set.
+* Make it a real daemon (demonize ? auto restarting support ?)
+* Same of the files needs to be separated from the rest of WebRuntime sources:
+    - global_config.cpp
+
diff --git a/src/daemon/dbus/org.tizen.SecurityDaemon.service b/src/daemon/dbus/org.tizen.SecurityDaemon.service
new file mode 100644 (file)
index 0000000..fc51772
--- /dev/null
@@ -0,0 +1,3 @@
+[D-BUS Service]
+Name=org.tizen.SecurityDaemon
+Exec=/usr/bin/wrt-security-daemon
diff --git a/src/daemon/dbus/security_daemon_dbus_config.h b/src/daemon/dbus/security_daemon_dbus_config.h
new file mode 100644 (file)
index 0000000..30b8d90
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        security_daemon_dbus_config.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains security daemon DBus configuration.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_DBUS_CONFIG_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_DBUS_CONFIG_H_
+
+#include <string>
+
+namespace WrtSecurity {
+
+struct SecurityDaemonConfig {
+    static const std::string OBJECT_PATH()
+    {
+        return "/org/tizen/SecurityDaemon";
+    }
+
+    static const std::string SERVICE_NAME()
+    {
+        return "org.tizen.SecurityDaemon";
+    }
+};
+
+} // namespace WrtSecurity
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_DBUS_CONFIG_H_
diff --git a/src/daemon/dbus/security_dbus_service.cpp b/src/daemon/dbus/security_dbus_service.cpp
new file mode 100644 (file)
index 0000000..303aa19
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        security_dbus_service.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @author      Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of security DBus service.
+ */
+#include <dpl/log/log.h>
+#include <algorithm>
+#include <gio/gio.h>
+#include <dpl/exception.h>
+#include <dpl/dbus/interface.h>
+#include <dpl/dbus/connection.h>
+#include "security_dbus_service.h"
+#include "security_daemon_dbus_config.h"
+#include <ace_server_dbus_interface.h>
+#include <ocsp_server_dbus_interface.h>
+#include <popup_response_dbus_interface.h>
+
+
+void SecurityDBusService::start()
+{
+    LogDebug("SecurityDBusService starting");
+    m_connection = DPL::DBus::Connection::systemBus();
+    std::for_each(m_objects.begin(),
+                  m_objects.end(),
+                  [this] (const DPL::DBus::ObjectPtr& object)
+                  {
+                      m_connection->registerObject(object);
+                  });
+    m_connection->registerService(
+            WrtSecurity::SecurityDaemonConfig::SERVICE_NAME());
+}
+
+void SecurityDBusService::stop()
+{
+    LogDebug("SecurityDBusService stopping");
+    m_connection.reset();
+}
+
+void SecurityDBusService::initialize()
+{
+    LogDebug("SecurityDBusService initializing");
+    g_type_init();
+
+    addInterface(WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+                 std::make_shared<RPC::AceServerDBusInterface>());
+    addInterface(WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+                 std::make_shared<RPC::OcspServerDBusInterface>());
+    addInterface(WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+                 std::make_shared<RPC::PopupResponseDBusInterface>());
+}
+
+void SecurityDBusService::addInterface(const std::string& objectPath,
+                                       const InterfaceDispatcherPtr& dispatcher)
+{
+    auto ifaces =
+        DPL::DBus::Interface::fromXMLString(dispatcher->getXmlSignature());
+    if (ifaces.empty())
+    {
+        ThrowMsg(DPL::Exception, "No interface description.");
+    }
+
+    auto iface = ifaces.at(0);
+    iface->setDispatcher(dispatcher.get());
+
+    m_dispatchers.push_back(dispatcher);
+    m_objects.push_back(DPL::DBus::Object::create(objectPath, iface));
+}
+
+void SecurityDBusService::deinitialize()
+{
+    LogDebug("SecurityDBusService deinitializing");
+    m_objects.clear();
+    m_dispatchers.clear();
+}
+
+#ifdef DBUS_CONNECTION
+DAEMON_REGISTER_SERVICE_MODULE(SecurityDBusService)
+#endif //DBUS_CONNECTION
diff --git a/src/daemon/dbus/security_dbus_service.h b/src/daemon/dbus/security_dbus_service.h
new file mode 100644 (file)
index 0000000..82fd627
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        security_dbus_service.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @author      Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions of security DBus service.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DBUS_SERVICE_H_
+#define WRT_SRC_RPC_SECURITY_DBUS_SERVICE_H_
+
+#include <memory>
+#include <vector>
+#include <dpl/dbus/connection.h>
+#include <dpl/dbus/object.h>
+#include <dpl/dbus/dispatcher.h>
+#include <dpl/dbus/dbus_interface_dispatcher.h>
+#include <security_daemon.h>
+
+class SecurityDBusService : public SecurityDaemon::DaemonService {
+private:
+    virtual void initialize();
+    virtual void start();
+    virtual void stop();
+    virtual void deinitialize();
+
+private:
+    typedef std::shared_ptr<DPL::DBus::InterfaceDispatcher> InterfaceDispatcherPtr;
+    typedef std::shared_ptr<DPL::DBus::Dispatcher> DispatcherPtr;
+
+    void addInterface(const std::string& objectPath,
+                      const InterfaceDispatcherPtr& dispatcher);
+
+    DPL::DBus::ConnectionPtr m_connection;
+    std::vector<DPL::DBus::ObjectPtr> m_objects;
+    std::vector<DispatcherPtr> m_dispatchers;
+};
+
+#endif // WRT_SRC_RPC_SECURITY_DBUS_SERVICE_H_
diff --git a/src/daemon/security_daemon.cpp b/src/daemon/security_daemon.cpp
new file mode 100644 (file)
index 0000000..f24f176
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        security_daemon.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This is implementation file of Security Daemon
+ */
+
+#include "security_daemon.h"
+
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+#include <dpl/log/log.h>
+#ifdef DBUS_CONNECTION
+#include <dpl/framework_efl.h>
+#endif
+
+#include <dpl/singleton_impl.h>
+IMPLEMENT_SINGLETON(SecurityDaemon::SecurityDaemon)
+
+#include <ace-dao-rw/AceDAO.h>
+
+namespace SecurityDaemon {
+
+SecurityDaemon::SecurityDaemon() :
+    m_initialized(false),
+    m_terminating(false),
+    m_returnValue(0)
+{
+}
+
+void SecurityDaemon::initialize(int& /*argc*/, char** /*argv*/)
+{
+    DPL::Log::LogSystemSingleton::Instance().SetTag("SECURITY_DAEMON");
+    LogDebug("Initializing");
+    Assert(!m_initialized && "Already Initialized");
+
+    DatabaseService::initialize();
+    FOREACH (service, m_servicesList) {
+        (*service)->initialize();
+    }
+    m_initialized = true;
+    LogDebug("Initialized");
+}
+
+int SecurityDaemon::execute()
+{
+    Assert(m_initialized && "Not Initialized");
+    LogDebug("Starting execute");
+    FOREACH (service, m_servicesList) {
+        (*service)->start();
+    }
+
+    return m_returnValue;
+}
+
+void SecurityDaemon::terminate(int returnValue)
+{
+    Assert(m_initialized && "Not Initialized");
+    Assert(!m_terminating && "Already terminating");
+    LogDebug("Terminating");
+
+    m_returnValue = returnValue;
+    m_terminating = true;
+
+    FOREACH (service, m_servicesList) {
+        (*service)->stop();
+    }
+}
+
+void SecurityDaemon::shutdown()
+{
+    LogDebug("Shutdown");
+    Assert(m_initialized && "Not Initialized");
+
+    DatabaseService::deinitialize();
+    FOREACH (service, m_servicesList) {
+        (*service)->deinitialize();
+    }
+
+    m_initialized = false;
+}
+
+namespace DatabaseService {
+
+void initialize(void)
+{
+    LogDebug("Ace/Wrt database services initializing...");
+    AceDB::AceDAO::attachToThreadRW();
+}
+
+void deinitialize(void)
+{
+    LogDebug("Ace/Wrt database services deinitializing...");
+    AceDB::AceDAO::detachFromThread();
+}
+
+} //namespace DatabaseService
+
+} //namespace SecurityDaemon
diff --git a/src/daemon/security_daemon.h b/src/daemon/security_daemon.h
new file mode 100644 (file)
index 0000000..a98f309
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        security_daemon.h
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This is header file of Security Daemon
+ */
+
+#ifndef WRT_SRC_SECURITY_DAEMON_SECURITY_DAEMON_H
+#define WRT_SRC_SECURITY_DAEMON_SECURITY_DAEMON_H
+
+#include <utility>
+#include <memory>
+#include <list>
+#include <dpl/noncopyable.h>
+#include <dpl/singleton.h>
+#include <dpl/assert.h>
+
+
+namespace SecurityDaemon {
+
+class DaemonService : DPL::Noncopyable {
+  public:
+    virtual void initialize() = 0;
+    virtual void start() = 0;
+    virtual void stop() = 0;
+    virtual void deinitialize() = 0;
+};
+
+class SecurityDaemon : DPL::Noncopyable
+{
+  public:
+    SecurityDaemon();
+
+    void initialize(int& argc, char** argv);
+    int execute();
+    void terminate(int returnValue = 0);
+
+    template<typename ServiceType, typename ...Args>
+    void registerService(Args&&... args)
+    {
+        Assert(!m_initialized && "Too late for registration");
+
+        m_servicesList.push_back(
+                std::make_shared<ServiceType>(std::forward<Args>(args)...));
+    }
+
+    void shutdown();
+
+  private:
+    bool m_initialized;
+    bool m_terminating;
+    int m_returnValue;
+    typedef std::list<std::shared_ptr<DaemonService>> DaemonServiceList;
+    DaemonServiceList m_servicesList;
+};
+
+namespace DatabaseService {
+    void initialize();
+    void deinitialize();
+};
+
+} //namespace SecurityDaemon
+
+typedef DPL::Singleton<SecurityDaemon::SecurityDaemon> SecurityDaemonSingleton;
+
+#define DAEMON_REGISTER_SERVICE_MODULE(Type)                                \
+    namespace {                                                             \
+        static int initializeModule();                                      \
+        static int initializeModuleHelper = initializeModule();             \
+        int initializeModule()                                              \
+        {                                                                   \
+            (void)initializeModuleHelper;                                   \
+            SecurityDaemonSingleton::Instance().registerService<Type>();    \
+            return 0;                                                       \
+        }                                                                   \
+    }
+
+
+#endif /* WRT_SRC_SECURITY_DAEMON_SECURITY_DAEMON_H */
diff --git a/src/daemon/sockets/api/callback_api.h b/src/daemon/sockets/api/callback_api.h
new file mode 100644 (file)
index 0000000..ddda4d4
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        callback_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This header provides types and exceptions required for security service callbacks
+ */
+
+#ifndef CALLBACK_API_H_
+#define CALLBACK_API_H_
+
+#include <dpl/exception.h>
+
+typedef void (*socketServerCallback) (SocketConnection * connector);
+
+typedef bool (*securityCheck) (int socketfd);
+
+namespace ServiceCallbackApi{
+
+    class Exception{
+    public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, ServiceCallbackException)
+    };
+
+}
+
+#endif /* CALLBACK_API_H_ */
diff --git a/src/daemon/sockets/security_daemon_socket_config.h b/src/daemon/sockets/security_daemon_socket_config.h
new file mode 100644 (file)
index 0000000..3d8b6f8
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        security_daemon_socket_config.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+
+#ifndef SECURITY_DAEMON_SOCKET_CONFIG_H_
+#define SECURITY_DAEMON_SOCKET_CONFIG_H_
+
+#include <string>
+#include <signal.h>
+
+namespace WrtSecurity {
+
+struct SecurityDaemonSocketConfig {
+    static const std::string SERVER_ADDRESS()
+    {
+        return "/tmp/server";
+    }
+};
+
+} // namespace WrtSecurity
+#endif /* SECURITY_DAEMON_SOCKET_CONFIG_H_ */
diff --git a/src/daemon/sockets/security_socket_service.cpp b/src/daemon/sockets/security_socket_service.cpp
new file mode 100644 (file)
index 0000000..fc7e730
--- /dev/null
@@ -0,0 +1,440 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        security_socket_service.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of socket server
+ */
+#include <systemd/sd-daemon.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/signalfd.h>
+#include <sys/select.h>
+#include <sys/stat.h>
+#include <signal.h>
+#include <fcntl.h>
+#include <cstring>
+#include <unistd.h>
+#include <dpl/log/log.h>
+#include "ace_service_callbacks_api.h"
+#include "ocsp_service_callbacks_api.h"
+#include "popup_service_callbacks_api.h"
+#include "security_daemon_socket_config.h"
+#include "security_socket_service.h"
+
+#define MAX_LISTEN 5
+#define SIGNAL_TO_CLOSE SIGUSR1
+
+void SecuritySocketService::throwWithErrnoMessage(const std::string& specificInfo){
+    LogError(specificInfo << " : " << strerror(errno));
+    ThrowMsg(DPL::Exception, specificInfo << " : " << strerror(errno));
+}
+
+void SecuritySocketService::registerServiceCallback(const std::string &interfaceName,
+                                                    const std::string &methodName,
+                                                    socketServerCallback callbackMethod,
+                                                    securityCheck securityMethod){
+    if(NULL == callbackMethod){
+        LogError("Null callback");
+        ThrowMsg(DPL::Exception, "Null callback");
+    }
+    if(interfaceName.empty() || methodName.empty()){
+        LogError("Interface and method name cannot be empty");
+        ThrowMsg(DPL::Exception, "Empty interface or method name");
+    }
+
+    auto serviceCallbackPtr = std::make_shared<ServiceCallback>(ServiceCallback(callbackMethod, securityMethod));
+    m_callbackMap[interfaceName][methodName] = serviceCallbackPtr;
+}
+
+void SecuritySocketService::addClientSocket(int clientSocket){
+    std::lock_guard<std::mutex> guard(m_clientSocketListMutex);
+    m_clientSocketList.push_back(clientSocket);
+}
+
+void SecuritySocketService::removeClientSocket(int clientSocket){
+    std::lock_guard<std::mutex> guard(m_clientSocketListMutex);
+    m_clientSocketList.remove(clientSocket);
+}
+
+bool SecuritySocketService::popClientSocket(int * clientSocket){
+    std::lock_guard<std::mutex> guard(m_clientSocketListMutex);
+    if(m_clientSocketList.empty())
+        return false;
+    *clientSocket = m_clientSocketList.front();
+    m_clientSocketList.pop_front();
+    return true;
+}
+
+int SecuritySocketService::get_systemd_socket(std::string &path) {
+
+       int type = SOCK_STREAM;
+       int listening = 1;
+       size_t length = 0;
+       int fd = -1;
+       int n;
+
+       // Gets number of created by systemd file descriptors that represent open sockets.
+       n = sd_listen_fds(1);
+
+       // Check open sockets count (must be 1)
+       if (n != 1)
+               return -1;
+
+       // File descriptor calculation
+       fd = SD_LISTEN_FDS_START  + 0;
+
+       // File descriptor veryfication.
+       if (sd_is_socket_unix(fd, type, listening, path.c_str(), length) > 0) {
+               activatedBySystemd = true;
+               return fd;
+       }
+
+       // No proper socket or error
+       return -1;
+}
+
+void SecuritySocketService::initialize(){
+
+    LogInfo("Initializing...");
+    m_serverAddress = WrtSecurity::SecurityDaemonSocketConfig::SERVER_ADDRESS();
+    m_signalToClose = SIGNAL_TO_CLOSE;
+
+    //registering Ace callbacks
+    registerServiceCallback(WrtSecurity::AceServerApi::INTERFACE_NAME(),
+                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().first,
+                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().second);
+
+    registerServiceCallback(WrtSecurity::AceServerApi::INTERFACE_NAME(),
+                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_INSTALL_METHOD_CALLBACK().first,
+                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_INSTALL_METHOD_CALLBACK().second);
+
+    registerServiceCallback(WrtSecurity::AceServerApi::INTERFACE_NAME(),
+                            WrtSecurity::AceServiceCallbacksApi::UPDATE_POLICY_METHOD_CALLBACK().first,
+                            WrtSecurity::AceServiceCallbacksApi::UPDATE_POLICY_METHOD_CALLBACK().second);
+    LogInfo("Registered Ace callbacks");
+
+    //registering Ocsp callbacks
+    registerServiceCallback(WrtSecurity::OcspServerApi::INTERFACE_NAME(),
+                            WrtSecurity::OcspServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().first,
+                            WrtSecurity::OcspServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().second);
+    LogInfo("Registered Ocsp callbacks");
+
+    //registering Popup callbacks
+    registerServiceCallback(WrtSecurity::PopupServerApi::INTERFACE_NAME(),
+                            WrtSecurity::PopupServiceCallbacksApi::VALIDATION_METHOD_CALLBACK().first,
+                            WrtSecurity::PopupServiceCallbacksApi::VALIDATION_METHOD_CALLBACK().second);
+    LogInfo("Registered Popup callbacks");
+
+    // Get systemd socket
+    activatedBySystemd = false;
+    m_listenFd = get_systemd_socket(m_serverAddress);
+    if (m_listenFd >= 0) {
+       LogInfo("Initialized");
+       return;
+    }
+
+    // Default socket initialization
+    if(-1 == (m_listenFd = socket(AF_UNIX, SOCK_STREAM, 0))){
+        throwWithErrnoMessage("socket()");
+    }
+    LogInfo("Server socket created");
+
+    //socket needs to be nonblocking, because read can block after select
+    int flags;
+    if (-1 == (flags = fcntl(m_listenFd, F_GETFL, 0)))
+        flags = 0;
+    if(-1 == (fcntl(m_listenFd, F_SETFL, flags | O_NONBLOCK))){
+        throwWithErrnoMessage("fcntl");
+    }
+
+    sockaddr_un server_address;
+    bzero(&server_address, sizeof(server_address));
+    server_address.sun_family = AF_UNIX;
+    strncpy(server_address.sun_path, m_serverAddress.c_str(), sizeof(server_address.sun_path) - 1);
+    unlink(server_address.sun_path);
+
+    mode_t socket_umask, original_umask;
+    socket_umask = 0;
+    original_umask = umask(socket_umask);
+
+    if(-1 == bind(m_listenFd, (struct sockaddr *)&server_address, SUN_LEN(&server_address))){
+        throwWithErrnoMessage("bind()");
+    }
+
+    umask(original_umask);
+
+    LogInfo("Initialized");
+}
+
+void SecuritySocketService::start(){
+
+    LogInfo("Starting...");
+    if(m_serverAddress.empty()){
+        LogError("Server not initialized");
+        ThrowMsg(DPL::Exception, "Server not initialized");
+    }
+
+    sigset_t sigset;
+    sigemptyset(&sigset);
+    if(-1 == sigaddset(&sigset, m_signalToClose)){
+        throwWithErrnoMessage("sigaddset()");
+    }
+    int returned_value;
+    if ((returned_value = pthread_sigmask(SIG_BLOCK, &sigset, NULL)) < 0) {
+        errno = returned_value;
+        throwWithErrnoMessage("pthread_sigmask()");
+    }
+
+    pthread_t mainThread;
+    if((returned_value = pthread_create(&mainThread, NULL, &serverThread, this)) < 0){
+        errno = returned_value;
+        throwWithErrnoMessage("pthread_create()");
+    }
+    m_mainThread = mainThread;
+
+    LogInfo("Started");
+}
+
+void * SecuritySocketService::serverThread(void * data){
+    pthread_detach(pthread_self());
+    SecuritySocketService &t = *static_cast<SecuritySocketService *>(data);
+    LogInfo("Running server main thread");
+    Try {
+        t.mainLoop();
+    } Catch (DPL::Exception) {
+        LogError("Socket server error. Exiting...");
+        return (void *)1;
+    }
+
+    return (void *)0;
+}
+
+
+void SecuritySocketService::mainLoop(){
+
+#ifdef ALL_LOGS
+       LogInfo("Server thread Main Loop : Started");
+#endif
+
+    if(!activatedBySystemd && listen(m_listenFd, MAX_LISTEN) == -1){
+        throwWithErrnoMessage("listen()");
+    }
+#ifdef ALL_LOGS
+       LogInfo("Server thread Main Loop : Listened something");
+#endif
+    //Settings to catch closing signal in select
+    int signal_fd;
+    sigset_t sigset;
+    if(-1 == (sigemptyset(&sigset))){
+        throwWithErrnoMessage("sigemptyset()");
+    }
+    if(-1 == (sigaddset(&sigset, m_signalToClose))) {
+        throwWithErrnoMessage("sigaddset()");
+    }
+    if((signal_fd = signalfd(-1, &sigset, 0)) < 0){
+        throwWithErrnoMessage("signalfd()");
+    }
+
+    //Setting descriptors for pselect
+    fd_set allset, rset;
+    int maxfd;
+    FD_ZERO(&allset);
+    FD_SET(m_listenFd, &allset);
+    FD_SET(signal_fd, &allset);
+    maxfd = (m_listenFd > signal_fd) ? (m_listenFd) : (signal_fd);
+    ++maxfd;
+    //this will block SIGPIPE for this thread and every thread created in it
+    //reason : from here on we don't won't to receive SIGPIPE on writing to closed socket
+    //instead of signal we want to receive error from write - hence blocking SIGPIPE
+    sigset_t set;
+    sigemptyset(&set);
+    sigaddset(&set, SIGPIPE);
+    pthread_sigmask(SIG_BLOCK, &set, NULL);
+#ifdef ALL_LOGS
+       LogInfo("Server thread Main Loop : Entering while loop.");
+#endif
+    while(1){
+        rset = allset;
+        if(-1 == pselect(maxfd, &rset, NULL, NULL, NULL, NULL)){
+            closeConnections();
+            throwWithErrnoMessage("pselect()");
+        }
+#ifdef ALL_LOGS
+               LogInfo("Server thread Main Loop : PSelected something.");
+#endif
+        if(FD_ISSET(signal_fd, &rset)){
+            LogInfo("Got signal to close");
+            signalfd_siginfo siginfo;
+            ssize_t res;
+            res = read(signal_fd, &siginfo, sizeof(siginfo));
+            if(res <= 0){
+                closeConnections();
+                throwWithErrnoMessage("read()");
+            }
+            if((size_t)res != sizeof(siginfo)){
+                closeConnections();
+                LogError("couldn't read whole siginfo");
+                ThrowMsg(DPL::Exception, "couldn't read whole siginfo");
+            }
+            if((int)siginfo.ssi_signo == m_signalToClose){
+                LogInfo("Server thread got signal to close");
+                closeConnections();
+                return;
+            } else {
+                LogInfo("Got not handled signal");
+            }
+        }
+        if(FD_ISSET(m_listenFd, &rset)){
+            int client_fd;
+#ifdef ALL_LOGS
+                       LogInfo("Server thread Main Loop : Client is there.");
+#endif
+            if(-1 == (client_fd = accept(m_listenFd, NULL, NULL))){
+                closeConnections();
+                throwWithErrnoMessage("accept()");
+            }
+            LogInfo("Got incoming connection");
+            Connection_Info * connection = new Connection_Info(client_fd, (void *)this);
+            int res;
+            pthread_t client_thread;
+            if((res = pthread_create(&client_thread, NULL, &connectionThread, connection)) < 0){
+                delete connection;
+                errno = res;
+                closeConnections();
+                throwWithErrnoMessage("pthread_create()");
+            }
+#ifdef ALL_LOGS
+                       LogInfo("Added incoming connection");
+#endif
+            addClientSocket(client_fd);
+        }
+    }
+}
+
+void * SecuritySocketService::connectionThread(void * data){
+    pthread_detach(pthread_self());
+    std::auto_ptr<Connection_Info> c (static_cast<Connection_Info *>(data));
+    SecuritySocketService &t = *static_cast<SecuritySocketService *>(c->data);
+#ifdef ALL_LOGS
+    LogInfo("Starting connection thread");
+#endif
+    Try {
+        t.connectionService(c->connfd);
+    } Catch (DPL::Exception){
+        LogError("Connection thread error : " << _rethrown_exception.DumpToString());
+        t.removeClientSocket(c->connfd);
+        close(c->connfd);
+        return (void*)1;
+    }
+#ifdef ALL_LOGS
+    LogInfo("Client serviced");
+#endif
+    return (void*)0;
+}
+
+void SecuritySocketService::connectionService(int fd){
+
+    SocketConnection connector = SocketConnection(fd);
+    std::string interfaceName, methodName;
+
+    Try {
+        connector.read(&interfaceName, &methodName);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection read error");
+        ReThrowMsg(DPL::Exception, "Socket Connection read error");
+    }
+#ifdef ALL_LOGS
+    LogDebug("Got interface : " << interfaceName);
+    LogDebug("Got method : " << methodName);
+#endif
+    if( m_callbackMap.find(interfaceName) == m_callbackMap.end()){
+        LogError("Unknown interface : " << interfaceName);
+        ThrowMsg(DPL::Exception, "Unknown interface : " << interfaceName);
+    }
+
+    if(m_callbackMap[interfaceName].find(methodName) == m_callbackMap[interfaceName].end()){
+        LogError("Unknown method : " << methodName);
+        ThrowMsg(DPL::Exception, "Unknown method");
+    }
+
+    if(m_callbackMap[interfaceName][methodName]->securityCallback != NULL){
+        if(!m_callbackMap[interfaceName][methodName]->securityCallback(fd)){
+            LogError("Security check returned false");
+            ThrowMsg(DPL::Exception, "Security check returned false");
+        }
+    }
+#ifdef ALL_LOGS
+    LogInfo("Calling service");
+#endif
+    Try{
+        m_callbackMap[interfaceName][methodName]->serviceCallback(&connector);
+    } Catch (ServiceCallbackApi::Exception::ServiceCallbackException){
+        LogError("Service callback error");
+        ReThrowMsg(DPL::Exception, "Service callback error");
+    }
+#ifdef ALL_LOGS
+    LogInfo("Removing client");
+#endif
+    removeClientSocket(fd);
+    close(fd);
+#ifdef ALL_LOGS
+    LogInfo("Call served");
+#endif
+
+}
+
+void SecuritySocketService::stop(){
+    LogInfo("Stopping");
+    if(-1 == close(m_listenFd))
+        if(errno != ENOTCONN)
+            throwWithErrnoMessage("close()");
+    int returned_value;
+    if((returned_value = pthread_kill(m_mainThread, m_signalToClose)) < 0){
+        errno = returned_value;
+        throwWithErrnoMessage("pthread_kill()");
+    }
+    pthread_join(m_mainThread, NULL);
+
+    LogInfo("Stopped");
+}
+
+void SecuritySocketService::closeConnections(){
+
+    int clientSocket;
+    LogInfo("Closing client sockets");
+    while(popClientSocket(&clientSocket)){
+        if(-1 == close(clientSocket)){
+            LogError("close() : " << strerror(errno));
+        }
+    }
+
+    LogInfo("Connections closed");
+}
+
+void SecuritySocketService::deinitialize(){
+    m_serverAddress.clear();
+
+    LogInfo("Deinitialized");
+
+}
+
+#ifdef SOCKET_CONNECTION
+DAEMON_REGISTER_SERVICE_MODULE(SecuritySocketService)
+#endif
diff --git a/src/daemon/sockets/security_socket_service.h b/src/daemon/sockets/security_socket_service.h
new file mode 100644 (file)
index 0000000..852838d
--- /dev/null
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        security_socket_service.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of socket server class
+ */
+
+#ifndef SECURITY_SOCKET_SERVICE_H_
+#define SECURITY_SOCKET_SERVICE_H_
+
+#include <map>
+#include <list>
+#include <memory>
+#include <mutex>
+#include <pthread.h>
+#include <security_daemon.h>
+#include <SocketConnection.h>
+#include <callback_api.h>
+
+class SecuritySocketService : public SecurityDaemon::DaemonService {
+
+private:
+  bool activatedBySystemd;
+  int get_systemd_socket(std::string &path);
+
+private:
+  virtual void initialize();
+  virtual void start();
+  virtual void stop();
+  virtual void deinitialize();
+
+
+private:
+
+    //Function for registering callback with given interface and method name and possibly security check callback
+    void registerServiceCallback(const std::string& interfaceName,
+                                 const std::string& methodName,
+                                 socketServerCallback serviceCallback,
+                                 securityCheck securityCallback = NULL);
+    //Thread function for server
+    static void * serverThread(void *);
+    //Main function for server
+    void mainLoop();
+    //Thread function for connection serving
+    static void * connectionThread(void *);
+    //Main function for connection serving
+    void connectionService(int fd);
+    //closing all connections
+    void closeConnections();
+    //logs an error and throws an exception with message containing errno message
+    void throwWithErrnoMessage(const std::string &specificInfo);
+
+    //concurrency safe methods for client socket list - add, remove and pop (with returned value)
+    void addClientSocket(int clientThread);
+    void removeClientSocket(int clientThread);
+    bool popClientSocket(int* clientThread);
+
+    //Address of socket server
+    std::string m_serverAddress;
+    //Signal used for informing threads to stop
+    int m_signalToClose;
+    //Socket for listening
+    int m_listenFd;
+    //Number of main thread
+    pthread_t m_mainThread;
+    //Numbers of all created threads for connections
+    std::list<int> m_clientSocketList;
+
+    //Thread list mutex
+    std::mutex m_clientSocketListMutex;
+
+    //Structure for callback maps
+    class ServiceCallback
+    {
+    public:
+        ServiceCallback(socketServerCallback ser, securityCheck sec) : serviceCallback(ser), securityCallback(sec){}
+        socketServerCallback serviceCallback;
+        securityCheck securityCallback;
+    };
+
+    typedef std::shared_ptr<ServiceCallback> ServiceCallbackPtr;
+    //Map for callback methods, key is a method name and value is a callback to method
+    typedef std::map<std::string, ServiceCallbackPtr> ServiceMethodCallbackMap;
+    //Map for interface methods, key is an interface name and value is a map of available methods with callbacks
+    std::map<std::string, ServiceMethodCallbackMap> m_callbackMap;
+
+    //Structure passed to connection thread
+    struct Connection_Info{
+        Connection_Info(int fd, void * data) : connfd(fd), data(data)
+        {}
+        int connfd;
+        void * data;
+    };
+
+};
+
+#endif /* SECURITY_SOCKET_SERVICE_H_ */
diff --git a/src/main.cpp b/src/main.cpp
new file mode 100644 (file)
index 0000000..608f939
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        main.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This is main routing for Security Daemon
+ */
+
+#include <systemd/sd-daemon.h>
+#include <dpl/log/log.h>
+#include <dpl/single_instance.h>
+#include <privacy_manager_daemon.h>
+
+#include "security_daemon.h"
+
+#include <pthread.h>
+#include <glib.h>
+#include <Ecore.h>
+
+static const std::string DAEMON_INSTANCE_UUID =
+    "5ebf3f24-dad6-4a27-88b4-df7970efe7a9";
+
+static Ecore_Event_Handler *g_exitHandler;
+static Eina_Bool exitHandler(void */*data*/, int /*type*/, void */*event*/)
+{
+    privacy_manager_daemon_stop();
+    privacy_manager_daemon_shutdown();
+
+    auto& daemon = SecurityDaemonSingleton::Instance();
+    daemon.shutdown();                   
+
+    ecore_event_handler_del(g_exitHandler);
+
+    ecore_main_loop_quit();
+
+    return ECORE_CALLBACK_CANCEL;
+}      
+
+static Eina_Bool startHandler(void */*data*/)
+{
+    int retVal;
+       auto& daemon = SecurityDaemonSingleton::Instance();
+       
+       privacy_manager_daemon_initialize();
+
+       privacy_manager_daemon_start();
+       
+       int argc = 0;
+       char* argv = NULL;
+
+       daemon.initialize(argc, &argv);
+    retVal = daemon.execute();
+    if (retVal != 0)
+    {
+        LogError("Failed to execute daemon.");
+        ecore_main_loop_quit();
+        
+        return ECORE_CALLBACK_CANCEL;
+    }
+
+       // Notification to systemd
+       sd_notify(0, "READY=1");
+
+    return ECORE_CALLBACK_CANCEL;
+}
+
+int main(int argc, char* argv[])
+{
+       DPL::SingleInstance instance;
+       
+       Try {
+               if (!instance.TryLock(DAEMON_INSTANCE_UUID)) {
+                       LogError("Security Daemon is already running");
+                       return -1;
+               }
+    } Catch (DPL::SingleInstance::Exception::LockError) {
+        LogError("Failed to lock/unlock Security Daemon instance.");
+        return -1;
+    }
+       
+    if (!ecore_init())
+    {
+        LogError("Ecore cannot be initialized");
+        return -1;
+    }
+       
+    ecore_timer_add(0.1, &startHandler, NULL);
+    g_exitHandler = ecore_event_handler_add(ECORE_EVENT_SIGNAL_EXIT, &exitHandler, NULL);
+    ecore_main_loop_begin();
+    ecore_shutdown();
+
+       Try {
+           instance.Release();
+    } Catch (DPL::SingleInstance::Exception::LockError) {
+        LogError("Failed to release Security Daemon instance.");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/src/services/ace/ace_server_api.h b/src/services/ace/ace_server_api.h
new file mode 100644 (file)
index 0000000..e327e31
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_server_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions of ACE server interface name & methods.
+ */
+
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_API_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_API_H_
+
+#include<string>
+
+
+namespace WrtSecurity{
+namespace AceServerApi{
+
+    // DBus interface names
+    inline const std::string INTERFACE_NAME()
+    {
+        return "org.tizen.AceCheckAccessInterface";
+    }
+
+    // IN string subject
+    // IN string resource
+    // IN vector<string> function param names
+    // IN vector<string> function param values
+    // OUT int allow, deny, popup type
+    inline const std::string CHECK_ACCESS_METHOD()
+    {
+        return "check_access";
+    }
+
+    // IN string subject
+    // IN string resource
+    // OUT int allow, deny, popup type
+    inline const std::string CHECK_ACCESS_INSTALL_METHOD()
+    {
+        return "check_access_install";
+    }
+
+    // Policy update trigger
+    inline const std::string UPDATE_POLICY_METHOD()
+    {
+        return "update_policy";
+    }
+};
+};
+
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_API_H_
diff --git a/src/services/ace/ace_service.cpp b/src/services/ace/ace_service.cpp
new file mode 100644 (file)
index 0000000..15227f4
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_service.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This is implementation file of AceService service
+ */
+
+#include <dpl/log/log.h>
+#include <security_controller.h>
+
+#include "security_daemon.h"
+
+namespace AceService
+{
+
+class AceService : public SecurityDaemon::DaemonService
+{
+  private:
+    virtual void initialize()
+    {
+        LogDebug("AceService initializing");
+
+        SecurityControllerSingleton::Instance().Touch();
+        SecurityControllerSingleton::Instance().SwitchToThread(NULL);
+
+        CONTROLLER_POST_SYNC_EVENT(
+            SecurityController,
+            SecurityControllerEvents::InitializeSyncEvent());
+    }
+
+    virtual void start()
+    {
+        LogDebug("Starting AceService");
+    }
+
+    virtual void stop()
+    {
+        LogDebug("Stopping AceService");
+    }
+
+    virtual void deinitialize()
+    {
+        LogDebug("AceService deinitializing");
+        SecurityControllerSingleton::Instance().SwitchToThread(NULL);
+        //this is direct call inside
+        CONTROLLER_POST_SYNC_EVENT(
+            SecurityController,
+            SecurityControllerEvents::TerminateSyncEvent());
+    }
+
+};
+
+DAEMON_REGISTER_SERVICE_MODULE(AceService)
+
+}//namespace AceService
diff --git a/src/services/ace/dbus/ace_server_dbus_interface.cpp b/src/services/ace/dbus/ace_server_dbus_interface.cpp
new file mode 100644 (file)
index 0000000..e77b9f9
--- /dev/null
@@ -0,0 +1,144 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_service_dbus_interface.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of ACE server API.
+ */
+#include <dpl/foreach.h>
+#include <vector>
+#include <string>
+#include "ace_server_dbus_interface.h"
+#include <dpl/dbus/dbus_server_deserialization.h>
+#include <dpl/dbus/dbus_server_serialization.h>
+
+#include <ace/Request.h>
+#include <ace/PolicyResult.h>
+#include <security_controller.h>
+#include <attribute_facade.h>
+
+
+namespace RPC {
+
+void AceServerDBusInterface::onMethodCall(const gchar* methodName,
+                          GVariant* parameters,
+                          GDBusMethodInvocation* invocation)
+{
+    using namespace WrtSecurity;
+
+    if (0 == g_strcmp0(methodName, AceServerApi::ECHO_METHOD().c_str()))
+    {
+        std::string str;
+        DPL::DBus::ServerDeserialization::deserialize(parameters, &str);
+        g_dbus_method_invocation_return_value(invocation,
+                DPL::DBus::ServerSerialization::serialize(str));
+    } else if (0 == g_strcmp0(methodName,
+                              AceServerApi::CHECK_ACCESS_METHOD().c_str()))
+    {
+        int widgetHandle;
+        std::string subject, resource, sessionId;
+        std::vector<std::string> paramNames, paramValues;
+        if (!DPL::DBus::ServerDeserialization::deserialize(parameters,
+                                                      &widgetHandle,
+                                                      &subject,
+                                                      &resource,
+                                                      &paramNames,
+                                                      &paramValues,
+                                                      &sessionId)) {
+            g_dbus_method_invocation_return_dbus_error(
+                          invocation,
+                          "org.tizen.AceCheckAccessInterface.UnknownError",
+                          "Error in deserializing input parameters");
+            return;
+        }
+        if (paramNames.size() != paramValues.size()) {
+            g_dbus_method_invocation_return_dbus_error(
+                      invocation,
+                      "org.tizen.AceCheckAccessInterface.UnknownError",
+                      "Varying sizes of parameter names and parameter values");
+            return;
+        }
+        LogDebug("We got subject: " << subject);
+        LogDebug("We got resource: " << resource);
+
+        FunctionParamImpl params;
+        for (size_t i = 0; i < paramNames.size(); ++i) {
+            params.addAttribute(paramNames[i], paramValues[i]);
+        }
+
+        Request request(widgetHandle,
+                        WidgetExecutionPhase_Invoke,
+                        &params);
+        request.addDeviceCapability(resource);
+
+        PolicyResult result(PolicyEffect::DENY);
+        CONTROLLER_POST_SYNC_EVENT(
+            SecurityController,
+            SecurityControllerEvents::CheckRuntimeCallSyncEvent(
+                &result,
+                &request,
+                sessionId));
+
+        int response = PolicyResult::serialize(result);
+        g_dbus_method_invocation_return_value(invocation,
+                DPL::DBus::ServerSerialization::serialize(response));
+    } else if (0 == g_strcmp0(methodName,
+            AceServerApi::CHECK_ACCESS_INSTALL_METHOD().c_str()))
+    {
+        int widgetHandle;
+        std::string resource;
+        if (!DPL::DBus::ServerDeserialization::deserialize(parameters,
+                                            &widgetHandle,
+                                            &resource)) {
+            g_dbus_method_invocation_return_dbus_error(
+                    invocation,
+                    "org.tizen.AceCheckAccessInterface.UnknownError",
+                    "Error in deserializing input parameters");
+            return;
+        }
+        LogDebug("We got handle: " << widgetHandle);
+        LogDebug("We got resource: " << resource);
+
+        Request request(widgetHandle,
+              WidgetExecutionPhase_WidgetInstall);
+        request.addDeviceCapability(resource);
+
+        PolicyResult result(PolicyEffect::DENY);
+        CONTROLLER_POST_SYNC_EVENT(
+        SecurityController,
+        SecurityControllerEvents::CheckFunctionCallSyncEvent(
+             &result,
+             &request));
+
+        int response = PolicyResult::serialize(result);
+        g_dbus_method_invocation_return_value(invocation,
+                DPL::DBus::ServerSerialization::serialize(response));
+    } else if (0 == g_strcmp0(methodName,
+            AceServerApi::UPDATE_POLICY_METHOD().c_str()))
+    {
+        LogDebug("Policy update DBus message received");
+        CONTROLLER_POST_SYNC_EVENT(
+                    SecurityController,
+                    SecurityControllerEvents::UpdatePolicySyncEvent());
+        g_dbus_method_invocation_return_value(invocation, NULL);
+    } else {
+        // invalid method name
+        g_dbus_method_invocation_return_value(invocation, NULL);
+    }
+}
+
+} // namespace RPC
diff --git a/src/services/ace/dbus/ace_server_dbus_interface.h b/src/services/ace/dbus/ace_server_dbus_interface.h
new file mode 100644 (file)
index 0000000..d5957cb
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_service_dbus_interface.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       Class that handles ACE server API.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_INTERFACE_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_INTERFACE_H_
+
+#include <dpl/dbus/dbus_interface_dispatcher.h>
+#include "api/ace_server_dbus_api.h"
+
+namespace RPC {
+
+class AceServerDBusInterface : public DPL::DBus::InterfaceDispatcher {
+  public:
+    AceServerDBusInterface():
+        DPL::DBus::InterfaceDispatcher(WrtSecurity::AceServerApi::INTERFACE_NAME())
+    {
+        using namespace WrtSecurity;
+
+        setXmlSignature("<node>"
+            "  <interface name='" + AceServerApi::INTERFACE_NAME() + "'>"
+            "    <method name='" + AceServerApi::ECHO_METHOD() + "'>"
+            "      <arg type='s' name='input' direction='in'/>"
+            "      <arg type='s' name='output' direction='out'/>"
+            "    </method>"
+            "    <method name='" + AceServerApi::CHECK_ACCESS_METHOD() + "'>"
+            "      <arg type='i' name='handle' direction='in'/>"
+            "      <arg type='s' name='subject' direction='in'/>"
+            "      <arg type='s' name='resource' direction='in'/>"
+            "      <arg type='as' name='parameter names' direction='in'/>"
+            "      <arg type='as' name='parameter values' direction='in'/>"
+            "      <arg type='s' name='session' direction='in'/>"
+            "      <arg type='i' name='output' direction='out'/>"
+            "    </method>"
+            "    <method name='" + AceServerApi::CHECK_ACCESS_INSTALL_METHOD() + "'>"
+            "      <arg type='i' name='handle' direction='in'/>"
+            "      <arg type='s' name='resource' direction='in'/>"
+            "      <arg type='i' name='output' direction='out'/>"
+            "    </method>"
+            "    <method name='" + AceServerApi::UPDATE_POLICY_METHOD() + "'>"
+            "    </method>"
+            "  </interface>"
+            "</node>");
+    }
+
+    virtual ~AceServerDBusInterface()
+    {}
+
+    virtual void onMethodCall(const gchar* methodName,
+                              GVariant* parameters,
+                              GDBusMethodInvocation* invocation);
+};
+
+} // namespace RPC
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_INTERFACE_H_
diff --git a/src/services/ace/dbus/api/ace_server_dbus_api.h b/src/services/ace/dbus/api/ace_server_dbus_api.h
new file mode 100644 (file)
index 0000000..9db4f05
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_server_api.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions ACE server interface & methods specifically needed by DBUS.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_API_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_API_H_
+
+#include "ace_server_api.h"
+#include<string>
+
+namespace WrtSecurity{
+namespace AceServerApi{
+
+    // RPC test function
+    // IN std::string
+    // OUT std::string
+    inline const std::string ECHO_METHOD()
+    {
+        return "echo";
+    }
+};
+};
+
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_API_H_
diff --git a/src/services/ace/logic/acf_consts.h b/src/services/ace/logic/acf_consts.h
new file mode 100644 (file)
index 0000000..93ecfae
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * This file contain consts for Signing Template and Policy Manager
+ * This values will be used to specified and identified algorithms in xml policy documents.
+ * Its consistent with BONDI 1.0 released requirements
+ *
+ * NOTE: This values should be verified when ACF will be updated to the latest version of BONDI requirements
+ * This values comes from widget digital signature 1.0 - required version of this doc is very important
+ *
+ **/
+
+#ifndef ACF_CONSTS_TYPES_H
+#define ACF_CONSTS_TYPES_H
+
+//Digest Algorithms
+extern const char* DIGEST_ALG_SHA256;
+
+//Canonicalization Algorithms
+extern const char* CANONICAL_ALG_C14N;
+
+//Signature Algorithms
+extern const char* SIGNATURE_ALG_RSA_with_SHA256;
+extern const char* SIGNATURE_ALG_DSA_with_SHA1;
+extern const char* SIGNATURE_ALG_ECDSA_with_SHA256;
+
+#endif
+
diff --git a/src/services/ace/logic/attribute_facade.cpp b/src/services/ace/logic/attribute_facade.cpp
new file mode 100644 (file)
index 0000000..faa43c6
--- /dev/null
@@ -0,0 +1,716 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ * This file contains classes that implement WRT_INTERFACE.h interfaces,
+ * so that ACE could access  WRT specific and other information during
+ * the decision making.
+ *
+ * @file    attribute_.cpp
+ * @author  Jaroslaw Osmanski (j.osmanski@samsung.com)
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @version 1.0
+ * @brief   Implementation file for attributes obtaining.
+ */
+
+#include <dpl/exception.h>
+#include <sstream>
+#include <algorithm>
+#include <list>
+#include <string>
+#include <sstream>
+#include <stdexcept>
+#include <map>
+#include <cstdlib>
+#include <ace-dao-ro/AceDAOReadOnly.h>
+#include <ace/WRT_INTERFACE.h>
+#include <map>
+#include <dpl/log/log.h>
+#include <dpl/foreach.h>
+#include <attribute_facade.h>
+#include <ace/Request.h>
+#include <simple_roaming_agent.h>
+
+namespace // anonymous
+{
+typedef std::list<std::string> AttributeHandlerResponse;
+
+typedef AttributeHandlerResponse (*AttributeHandler)(
+    const WidgetExecutionPhase &phase,
+    const WidgetHandle &widgetHandle);
+typedef AttributeHandlerResponse (*ResourceAttributeHandler)(
+    const WidgetExecutionPhase &phase,
+    const WidgetHandle &widgetHandle,
+    const Request &request);
+
+AttributeHandlerResponse AttributeClassHandler(const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle & /*widgetHandle*/)
+{
+    AttributeHandlerResponse response;
+    response.push_back("widget");
+    return response;
+}
+
+AttributeHandlerResponse AttributeInstallUriHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    std::string value = AceDB::AceDAOReadOnly::getShareHref(widgetHandle);
+    if(!value.empty())
+        response.push_back(value);
+    return response;
+}
+
+AttributeHandlerResponse AttributeVersionHandler(const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+
+    std::string value = AceDB::AceDAOReadOnly::getVersion(widgetHandle);
+
+    if (!value.empty()) {
+        response.push_back(value);
+    }
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
+        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ENDENTITY);
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
+        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ENDENTITY);
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyRootCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
+        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ROOT);
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyRootFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
+        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ROOT);
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
+        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ENDENTITY);
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
+        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ENDENTITY);
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyRootCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
+        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ROOT);
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyRootFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
+        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ROOT);
+    return response;
+}
+
+AttributeHandlerResponse AttributeNetworkAccessUriHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle & /*widgetHandle*/)
+{
+    AttributeHandlerResponse response;
+    return response;
+}
+
+AttributeHandlerResponse AttributeIdHandler(const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+
+    std::string wGUID = AceDB::AceDAOReadOnly::getGUID(widgetHandle);
+
+    if (!wGUID.empty()) {
+        response.push_back(wGUID);
+    }
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorNameHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+
+    std::string value = AceDB::AceDAOReadOnly::getAuthorName(widgetHandle);
+
+    if (!value.empty()) {
+        response.push_back(value);
+    }
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeRoamingHandler(
+        const WidgetExecutionPhase &phase,
+        const WidgetHandle & /*widgetHandle*/)
+{
+    AttributeHandlerResponse response;
+
+    if (WidgetExecutionPhase_WidgetInstall == phase) {
+        // TODO undetermind value
+        response.push_back(std::string(""));
+    } else if (SimpleRoamingAgentSingleton::Instance().IsRoamingOn()) {
+        response.push_back(std::string("true"));
+    } else {
+        response.push_back(std::string("false"));
+    }
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeBearerTypeHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle & /*widgetHandle*/)
+{
+    AttributeHandlerResponse response;
+
+    std::string bearerName = "undefined-bearer-name";
+
+    if (bearerName.empty()) {
+        LogWarning("Bearer-type is NOT SET or empty");
+    } else {
+        response.push_back(bearerName);
+    }
+
+    return response;
+}
+
+struct AttributeHandlerContext
+{
+    std::string name;
+    WidgetExecutionPhase allowedPhaseMask;
+    AttributeHandler handler;
+};
+
+// Private masks
+const WidgetExecutionPhase WidgetExecutionPhase_All =
+    static_cast<WidgetExecutionPhase>(
+        WidgetExecutionPhase_WidgetInstall |
+        WidgetExecutionPhase_WidgetInstantiate |
+        WidgetExecutionPhase_WebkitBind |
+        WidgetExecutionPhase_Invoke);
+const WidgetExecutionPhase WidgetExecutionPhase_NoWidgetInstall =
+    static_cast<WidgetExecutionPhase>(
+        WidgetExecutionPhase_WidgetInstantiate |
+        WidgetExecutionPhase_WebkitBind |
+        WidgetExecutionPhase_Invoke);
+
+#define ALL_PHASE(name, handler) \
+    { # name, WidgetExecutionPhase_All, handler },
+
+#define NO_INSTALL(name, handler) \
+    { # name, WidgetExecutionPhase_NoWidgetInstall, handler },
+
+AttributeHandlerContext HANDLED_ATTRIBUTES_LIST[] = {
+    ALL_PHASE(Class, &AttributeClassHandler)
+    ALL_PHASE(install-uri, &AttributeInstallUriHandler)
+    ALL_PHASE(version, &AttributeVersionHandler)
+    ALL_PHASE(distributor-key-cn, &AttributeDistributorKeyCnHandler)
+    ALL_PHASE(distributor-key-fingerprint,
+              &AttributeDistributorKeyFingerprintHandler)
+    ALL_PHASE(distributor-key-root-cn,
+              &AttributeDistributorKeyRootCnHandler)
+    ALL_PHASE(distributor-key-root-fingerprint,
+              &AttributeDistributorKeyRootFingerprintHandler)
+    ALL_PHASE(author-key-cn, &AttributeAuthorKeyCnHandler)
+    ALL_PHASE(author-key-fingerprint, &AttributeAuthorKeyFingerprintHandler)
+    ALL_PHASE(author-key-root-cn, &AttributeAuthorKeyRootCnHandler)
+    ALL_PHASE(author-key-root-fingerprint,
+              &AttributeAuthorKeyRootFingerprintHandler)
+    ALL_PHASE(network-access-uri, &AttributeNetworkAccessUriHandler)
+    ALL_PHASE(id, &AttributeIdHandler)
+//    ALL_PHASE(name, &AttributeNameHandler)
+//    ALL_PHASE(widget-attr:name, &AttributeWidgetAttrNameHandler)
+    ALL_PHASE(author-name, &AttributeAuthorNameHandler)
+    /* Enviroment  attributes*/
+//    NO_INSTALL(roaming, &AttributeRoamingHandler)
+//    NO_INSTALL(bearer-type, &AttributeBearerTypeHandler)
+};
+
+#undef ALL_PHASE
+#undef NO_INSTALL
+
+const size_t HANDLED_ATTRIBUTES_LIST_COUNT =
+    sizeof(HANDLED_ATTRIBUTES_LIST) / sizeof(HANDLED_ATTRIBUTES_LIST[0]);
+
+template<class T>
+class lambdaCollectionPusher
+{
+  public:
+    std::list<T>& m_collection;
+    lambdaCollectionPusher(std::list<T>& collection) : m_collection(collection)
+    {
+    }
+    void operator()(const T& element) const
+    {
+        m_collection.push_back(element);
+    }
+};
+
+AttributeHandlerResponse AttributeDeviceCapHandler(const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle & /*widgetHandle*/,
+        const Request &request)
+{
+    AttributeHandlerResponse response;
+
+    Request::DeviceCapabilitySet capSet = request.getDeviceCapabilitySet();
+    LogDebug("device caps set contains");
+    FOREACH(dc, capSet)
+    {
+        LogDebug("-> " << *dc);
+    }
+
+    std::for_each(
+        capSet.begin(),
+        capSet.end(),
+        lambdaCollectionPusher<std::string>(response));
+
+    return response;
+}
+
+//class lambdaFeatureEquality :
+//    public std::binary_function<FeatureHandle, int, bool>
+//{
+//  public:
+//    bool operator()(const FeatureHandle& wFeature,
+//            const int& resurceId) const
+//    {
+//        return wFeature == resurceId;
+//    }
+//};
+//
+//class lambdaPushFeatureName :
+//    public std::binary_function<WidgetFeature, AttributeHandlerResponse, void>
+//{
+//    void operator()(const WidgetFeature& wFeature,
+//            AttributeHandlerResponse& response) const
+//    {
+//        response.push_back(DPL::ToUTF8String(wFeature.name));
+//    }
+//};
+
+AttributeHandlerResponse AttributeApiFeatureHandler(
+        const WidgetExecutionPhase & /* phase */,
+        const WidgetHandle & /* widgetHandle */,
+        const Request & /* request */)
+{
+    LogDebug("WAC 2.0 does not support api-feature and resource-id in policy.");
+    AttributeHandlerResponse response;
+    return response;
+}
+
+AttributeHandlerResponse AttributeFeatureInstallUriHandler(
+        const WidgetExecutionPhase & /* phase */,
+        const WidgetHandle & /* widgetHandle */,
+        const Request & /* request */)
+{
+    LogDebug("WAC 2.0 does not support feature-install-uri is policy!");
+    AttributeHandlerResponse response;
+    return response;
+}
+
+AttributeHandlerResponse AttributeFeatureFeatureKeyCnHandler(
+        const WidgetExecutionPhase & /* phase */,
+        const WidgetHandle & /* widgetHandle */,
+        const Request & /* request */)
+{
+    LogDebug("WAC 2.0 does not support feature-key-cn is policy!");
+    AttributeHandlerResponse response;
+    return response;
+}
+
+AttributeHandlerResponse AttributeFeatureKeyRootCnHandler(
+        const WidgetExecutionPhase & /* phase */,
+        const WidgetHandle & /* widgetHandle */,
+        const Request & /* request */)
+{
+    LogDebug("WAC 2.0 does not support feature-key-root-cn is policy!");
+    AttributeHandlerResponse response;
+    return response;
+}
+
+AttributeHandlerResponse AttributeFeatureKeyRootFingerprintHandler(
+        const WidgetExecutionPhase & /* phase */,
+        const WidgetHandle & /* widgetHandle */,
+        const Request & /* request */)
+{
+    LogDebug("WAC 2.0 does not support"
+        " feature-key-root-fingerprint is policy!");
+    AttributeHandlerResponse response;
+    return response;
+}
+
+struct ResourceAttributeHandlerContext
+{
+    std::string name;
+    WidgetExecutionPhase allowedPhaseMask;
+    ResourceAttributeHandler handler;
+};
+
+#define ALL_PHASE(name, handler) \
+    { # name, WidgetExecutionPhase_All, handler },
+
+ResourceAttributeHandlerContext HANDLED_RESOURCE_ATTRIBUTES_LIST[] = {
+    ALL_PHASE(device-cap, &AttributeDeviceCapHandler)
+    ALL_PHASE(api-feature, &AttributeApiFeatureHandler)
+    // For compatiblity with older policies we tread resource-id
+    // identically as api-feature
+    ALL_PHASE(resource-id, &AttributeApiFeatureHandler)
+
+    ALL_PHASE(feature-install-uri, &AttributeFeatureInstallUriHandler)
+    ALL_PHASE(feature-key-cn, &AttributeFeatureFeatureKeyCnHandler)
+    ALL_PHASE(feature-key-root-cn, &AttributeFeatureKeyRootCnHandler)
+    ALL_PHASE(feature-key-root-fingerprint,
+              &AttributeFeatureKeyRootFingerprintHandler)
+};
+
+#undef ALL_PHASE
+
+const size_t HANDLED_RESOURCE_ATTRIBUTES_LIST_COUNT =
+    sizeof(HANDLED_RESOURCE_ATTRIBUTES_LIST) /
+    sizeof(HANDLED_RESOURCE_ATTRIBUTES_LIST[0]);
+} // namespace anonymous
+
+/*
+ * class WebRuntimeImpl
+ */
+int WebRuntimeImpl::getAttributesValuesLoop(const Request &request,
+        std::list<ATTRIBUTE>* attributes,
+        WidgetExecutionPhase executionPhase)
+{
+    UNHANDLED_EXCEPTION_HANDLER_BEGIN
+    {
+        WidgetHandle widgetHandle = request.getWidgetHandle();
+
+        FOREACH(itr, *attributes)
+        {
+            // Get attribute name
+            std::string attribute = *itr->first;
+
+            // Search for attribute handler
+            bool attributeFound = false;
+
+            for (size_t i = 0; i < HANDLED_ATTRIBUTES_LIST_COUNT; ++i) {
+                if (HANDLED_ATTRIBUTES_LIST[i].name == attribute) {
+                    // Check if execution phase is valid
+                    if ((executionPhase &
+                         HANDLED_ATTRIBUTES_LIST[i].allowedPhaseMask) == 0) {
+                        // Attribute found, but execution state
+                        // forbids to execute handler
+                        LogWarning(
+                            "Request for attribute: '" <<
+                            attribute << "' which is supported " <<
+                            "but forbidden at widget execution phase: "
+                            <<
+                            executionPhase);
+                    } else {
+                        // Execution phase allows handler
+                        AttributeHandlerResponse attributeResponse =
+                            (*HANDLED_ATTRIBUTES_LIST[i].handler)(
+                                executionPhase,
+                                widgetHandle);
+                        std::copy(attributeResponse.begin(),
+                                  attributeResponse.end(),
+                                  std::back_inserter(*itr->second));
+                    }
+
+                    attributeFound = true;
+                    break;
+                }
+            }
+
+            if (!attributeFound) {
+                LogWarning("Request for attribute: '" <<
+                           attribute << "' which is not supported");
+            }
+        }
+
+        return 0;
+    }
+    UNHANDLED_EXCEPTION_HANDLER_END
+}
+
+int WebRuntimeImpl::getAttributesValues(const Request &request,
+        std::list<ATTRIBUTE>* attributes)
+{
+    UNHANDLED_EXCEPTION_HANDLER_BEGIN
+    {
+        // Get current execution state
+        WidgetExecutionPhase executionPhase =
+            request.getExecutionPhase();
+
+        return getAttributesValuesLoop(request, attributes, executionPhase);
+    }
+    UNHANDLED_EXCEPTION_HANDLER_END
+}
+
+std::string WebRuntimeImpl::getSessionId(const Request & /* request */)
+{
+    std::string result;
+    LogError("Not implemented!");
+    return result;
+}
+
+WebRuntimeImpl::WebRuntimeImpl()
+{
+}
+
+/*
+ * class ResourceInformationImpl
+ */
+
+int ResourceInformationImpl::getAttributesValuesLoop(const Request &request,
+        std::list<ATTRIBUTE>* attributes,
+        WidgetExecutionPhase executionPhase)
+{
+    // Currently, we assume widgets have internal representation of integer IDs
+    WidgetHandle widgetHandle = request.getWidgetHandle();
+    //TODO add resource id string analyzys
+    FOREACH(itr, *attributes)
+    {
+        // Get attribute name
+        std::string attribute = *itr->first;
+        LogDebug("getting attribute value for: " << attribute);
+        FOREACH(aaa, *itr->second)
+        {
+            LogDebug("its value is: " << *aaa);
+        }
+
+        // Search for attribute handler
+        bool attributeFound = false;
+
+        for (size_t i = 0; i < HANDLED_RESOURCE_ATTRIBUTES_LIST_COUNT; ++i) {
+            if (HANDLED_RESOURCE_ATTRIBUTES_LIST[i].name == attribute) {
+                // Check if execution phase is valid
+                if ((executionPhase &
+                     HANDLED_RESOURCE_ATTRIBUTES_LIST[i].allowedPhaseMask) ==
+                    0) {
+                    // Attribute found, but execution state
+                    // forbids to execute handler
+                    LogDebug(
+                        "Request for attribute: '" <<
+                        attribute <<
+                        "' which is supported but forbidden " <<
+                        "at widget execution phase: " << executionPhase);
+                    itr->second = NULL;
+                } else {
+                    // Execution phase allows handler
+                    AttributeHandlerResponse attributeResponse =
+                        (*HANDLED_RESOURCE_ATTRIBUTES_LIST[i].handler)(
+                            executionPhase,
+                            widgetHandle,
+                            request);
+                    std::copy(attributeResponse.begin(),
+                              attributeResponse.end(),
+                              std::back_inserter(*itr->second));
+
+                    std::ostringstream attributeResponseFull;
+
+                    for (AttributeHandlerResponse::const_iterator
+                         it = attributeResponse.begin();
+                         it != attributeResponse.end(); ++it) {
+                        attributeResponseFull <<
+                        (it == attributeResponse.begin() ? "" : ", ") <<
+                        *it;
+                    }
+
+                    LogDebug("Attribute(" << attribute << ") = " <<
+                             attributeResponseFull.str());
+                }
+
+                attributeFound = true;
+                break;
+            }
+        }
+
+        if (!attributeFound) {
+            LogWarning("Request for attribute: '" << attribute <<
+                       "' which is not supported");
+        }
+    }
+    return 0;
+}
+
+int ResourceInformationImpl::getAttributesValues(const Request &request,
+        std::list<ATTRIBUTE>* attributes)
+{
+    UNHANDLED_EXCEPTION_HANDLER_BEGIN
+    {
+        // Get current execution state
+        WidgetExecutionPhase executionPhase =
+            request.getExecutionPhase();
+        return getAttributesValuesLoop(request, attributes, executionPhase);
+    }
+    UNHANDLED_EXCEPTION_HANDLER_END
+}
+
+ResourceInformationImpl::ResourceInformationImpl()
+{
+}
+
+/*
+ * class OperationSystemImpl
+ */
+
+int OperationSystemImpl::getAttributesValues(const Request &request,
+        std::list<ATTRIBUTE>* attributes)
+{
+    UNHANDLED_EXCEPTION_HANDLER_BEGIN
+    {
+        //FIXME:
+        //GetExecution name without widget name
+        WidgetExecutionPhase executionPhase =
+            request.getExecutionPhase();
+
+        FOREACH(itr, *attributes)
+        {
+            // Get attribute name
+            std::string attribute = *itr->first;
+
+            // Search for attribute handler
+            bool attributeFound = false;
+
+            for (size_t i = 0; i < HANDLED_ATTRIBUTES_LIST_COUNT; ++i) {
+                if (HANDLED_ATTRIBUTES_LIST[i].name == attribute) {
+                    // Check if execution phase is valid
+                    if ((executionPhase &
+                         HANDLED_ATTRIBUTES_LIST[i].allowedPhaseMask) == 0) {
+                        // Attribute found, but execution state forbids
+                        // to execute handler
+                        LogDebug("Request for attribute: '" << attribute <<
+                                 "' which is supported but forbidden at " <<
+                                 "widget execution phase: " << executionPhase);
+                        itr->second = NULL;
+                    } else {
+                        // Execution phase allows handler
+                        AttributeHandlerResponse attributeResponse =
+                            (*HANDLED_ATTRIBUTES_LIST[i].handler)(
+                                executionPhase,
+                                0);
+                        std::copy(attributeResponse.begin(),
+                                  attributeResponse.end(),
+                                  std::back_inserter(*itr->second));
+
+                        std::ostringstream attributeResponseFull;
+
+                        typedef AttributeHandlerResponse::const_iterator Iter;
+                        FOREACH(it, attributeResponse)
+                        {
+                            attributeResponseFull <<
+                            (it == attributeResponse.begin()
+                             ? "" : ", ") << *it;
+                        }
+
+                        LogDebug("Attribute(" << attribute <<
+                                 ") = " << attributeResponseFull.str());
+                    }
+
+                    attributeFound = true;
+                    break;
+                }
+            }
+
+            if (!attributeFound) {
+                LogWarning("Request for attribute: '" << attribute <<
+                           "' which is not supported");
+            }
+        }
+
+        return 0;
+    }
+    UNHANDLED_EXCEPTION_HANDLER_END
+}
+
+OperationSystemImpl::OperationSystemImpl()
+{
+}
+
+/*
+ * end of class OperationSystemImpl
+ */
+
+int FunctionParamImpl::getAttributesValues(const Request & /*request*/,
+        std::list<ATTRIBUTE> *attributes)
+{
+    FOREACH(iter, *attributes)
+    {
+        std::string attributeName = *(iter->first);
+
+        ParamMap::const_iterator i;
+        std::pair<ParamMap::const_iterator, ParamMap::const_iterator> jj =
+            paramMap.equal_range(attributeName);
+
+        for (i = jj.first; i != jj.second; ++i) {
+            iter->second->push_back(i->second);
+            LogDebug("Attribute: " << attributeName << " Value: " <<
+                     i->second);
+        }
+    }
+    return 0;
+}
diff --git a/src/services/ace/logic/attribute_facade.h b/src/services/ace/logic/attribute_facade.h
new file mode 100644 (file)
index 0000000..7b6898c
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file    attribute_facade.h
+ * @author  Jaroslaw Osmanski (j.osmanski@samsung.com)
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version 1.0
+ * @brief   This file contains the declaration of WebRuntimeImpl,
+ *          ResourceInformationImpl, OperationSystemImpl
+ */
+
+#ifndef ATTRIBUTE_FACADE_H
+#define ATTRIBUTE_FACADE_H
+
+#include <string>
+#include <map>
+#include <vector>
+
+#include <ace/WRT_INTERFACE.h>
+
+class Request;
+
+class WebRuntimeImpl : public IWebRuntime
+{
+  public:
+    // Return current sessionId
+    int getAttributesValuesLoop(const Request &request,
+            std::list<ATTRIBUTE>* attributes,
+            WidgetExecutionPhase executionPhase);
+
+    int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE>* attributes);
+    virtual std::string getSessionId(const Request &request);
+    WebRuntimeImpl();
+};
+
+class ResourceInformationImpl : public IResourceInformation
+{
+  public:
+    int getAttributesValuesLoop(const Request &request,
+            std::list<ATTRIBUTE>* attributes,
+            WidgetExecutionPhase executionPhase);
+    int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE>* attributes);
+    ResourceInformationImpl();
+};
+
+class OperationSystemImpl : public IOperationSystem
+{
+  public:
+    /**
+     * gather and set attributes values for specified attribute name
+     * @param attributes is a list of pairs(
+     *   first:   pointer to attribute name
+     *   second: list of values for attribute (std::string)  -
+     *   its a list of string (BONDI requirement), but usually there
+     *   will be only one string
+     */
+    int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE>* attributes);
+    OperationSystemImpl();
+};
+
+class FunctionParamImpl : public IFunctionParam
+{
+  public:
+    virtual int getAttributesValues(const Request & /*request*/,
+            std::list<ATTRIBUTE> *attributes);
+    void addAttribute(const std::string &key,
+            const std::string &value)
+    {
+        paramMap.insert(make_pair(key, value));
+    }
+    virtual ~FunctionParamImpl()
+    {
+    }
+
+  private:
+    typedef std::multimap<std::string, std::string> ParamMap;
+    ParamMap paramMap;
+};
+
+typedef std::vector <FunctionParamImpl> FunctionParams;
+
+#endif //ATTRIBUTE_FACADE_H
diff --git a/src/services/ace/logic/security_controller.cpp b/src/services/ace/logic/security_controller.cpp
new file mode 100644 (file)
index 0000000..a0fe874
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This class simply redirects the access requests to access control engine.
+ * The aim is to hide access control engine specific details from WRT modules.
+ * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
+ * WRT specific and other information during the decision making.
+ *
+ * @file    security_controller.cpp
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @version 1.0
+ * @brief   Implementation file for security controller
+ */
+#include <security_controller.h>
+#include <ace/PolicyEnforcementPoint.h>
+#include <ace/WRT_INTERFACE.h>
+//#include <engine/PolicyEvaluatorFactory.h>
+//#include <logic/attribute_facade.h>
+#include <dpl/singleton_impl.h>
+#include <dpl/log/log.h>
+#include <security_logic.h>
+#include <security_caller.h>
+
+IMPLEMENT_SINGLETON(SecurityController)
+
+struct SecurityController::Impl
+{
+    SecurityLogic logic;
+};
+
+SecurityController::SecurityController()
+{
+    m_impl.reset(new Impl);
+}
+
+SecurityController::~SecurityController()
+{
+}
+
+void SecurityController::OnEventReceived(
+    const SecurityControllerEvents::InitializeSyncEvent & /* event */)
+{
+    SecurityCallerSingleton::Instance().Run();
+    m_impl->logic.initialize();
+}
+
+void SecurityController::OnEventReceived(
+        const SecurityControllerEvents::UpdatePolicySyncEvent& /* event */)
+{
+    m_impl->logic.updatePolicy();
+}
+
+void SecurityController::OnEventReceived(
+    const SecurityControllerEvents::TerminateSyncEvent & /*event*/)
+{
+    SecurityCallerSingleton::Instance().Quit();
+    m_impl->logic.terminate();
+}
+
+void SecurityController::OnEventReceived(
+    const SecurityControllerEvents::CheckFunctionCallSyncEvent &ev)
+{
+    *ev.GetArg0() = m_impl->logic.checkFunctionCall(ev.GetArg1());
+}
+
+void SecurityController::OnEventReceived(
+    const SecurityControllerEvents::CheckRuntimeCallSyncEvent &ev)
+{
+    *ev.GetArg0() = m_impl->logic.checkFunctionCall(ev.GetArg1(), ev.GetArg2());
+}
+
+void SecurityController::OnEventReceived(
+           const SecurityControllerEvents::ValidatePopupResponseEvent &ev)
+{
+    m_impl->logic.validatePopupResponse(ev.GetArg0(),
+                                        ev.GetArg1(),
+                                        ev.GetArg2(),
+                                        ev.GetArg3(),
+                                        ev.GetArg4());
+}
diff --git a/src/services/ace/logic/security_controller.h b/src/services/ace/logic/security_controller.h
new file mode 100644 (file)
index 0000000..d122420
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This class simply redirects the access requests to access control engine.
+ * The aim is to hide access control engine specific details from WRT modules.
+ * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
+ * WRT specific and other information during the decision making.
+ *
+ * @file    security_controller.h
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @version 1.0
+ * @brief   Header file for security controller
+ */
+#ifndef SECURITY_CONTROLLER_H
+#define SECURITY_CONTROLLER_H
+
+#include <dpl/singleton.h>
+#include <dpl/event/controller.h>
+#include <dpl/generic_event.h>
+#include <dpl/type_list.h>
+#include <string>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace/AbstractPolicyEnforcementPoint.h>
+#include <ace-dao-ro/PromptModel.h>
+#include <string>
+#include <dpl/event/inter_context_delegate.h>
+
+namespace Jobs {
+class Job;
+}
+
+namespace SecurityControllerEvents {
+DECLARE_GENERIC_EVENT_0(InitializeSyncEvent)
+DECLARE_GENERIC_EVENT_0(TerminateSyncEvent)
+DECLARE_GENERIC_EVENT_0(UpdatePolicySyncEvent)
+
+DECLARE_GENERIC_EVENT_2(CheckFunctionCallSyncEvent,
+                        PolicyResult *,
+                        Request *
+                       )
+
+DECLARE_GENERIC_EVENT_3(CheckRuntimeCallSyncEvent,
+                        PolicyResult *,
+                        Request *,
+                        std::string //sessionId
+                       )
+
+DECLARE_GENERIC_EVENT_5(ValidatePopupResponseEvent,
+                        Request *,
+                        bool, //is allowed
+                        Prompt::Validity,
+                        std::string, //sessionId
+                        bool* //check return value
+                       )
+
+} // namespace SecurityControllerEvents
+
+typedef DPL::TypeListDecl<
+    SecurityControllerEvents::InitializeSyncEvent,
+    SecurityControllerEvents::TerminateSyncEvent,
+    SecurityControllerEvents::UpdatePolicySyncEvent,
+    SecurityControllerEvents::ValidatePopupResponseEvent,
+    SecurityControllerEvents::CheckRuntimeCallSyncEvent,
+    SecurityControllerEvents::CheckFunctionCallSyncEvent>::Type
+SecurityControllerEventsTypeList;
+
+class SecurityController :
+        public DPL::Event::Controller<SecurityControllerEventsTypeList>
+{
+  protected:
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::InitializeSyncEvent &event);
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::UpdatePolicySyncEvent &event);
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::ValidatePopupResponseEvent &e);
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::TerminateSyncEvent &event);
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::CheckFunctionCallSyncEvent &e);
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::CheckRuntimeCallSyncEvent &e);
+
+  private:
+    class Impl;
+    std::unique_ptr<Impl> m_impl;
+
+    SecurityController();
+    //This desctructor must be in implementation file (cannot be autogenerated)
+    ~SecurityController();
+
+    friend class DPL::Singleton<SecurityController>;
+};
+
+typedef DPL::Singleton<SecurityController> SecurityControllerSingleton;
+
+#endif // SECURITY_CONTROLLER_H
diff --git a/src/services/ace/logic/security_logic.cpp b/src/services/ace/logic/security_logic.cpp
new file mode 100644 (file)
index 0000000..5448fc0
--- /dev/null
@@ -0,0 +1,386 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This class simply redirects the access requests to access control engine.
+ * The aim is to hide access control engine specific details from WRT modules.
+ * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
+ * WRT specific and other information during the decision making.
+ *
+ * @file    security_controller.h
+ # @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @author  Piotr Kozbial (p.kozbial@samsung.com)
+ * @version 1.0
+ * @brief   Header file for security logic
+ */
+
+#include <security_logic.h>
+#include <attribute_facade.h>
+#ifdef WRT_SMACK_ENABLED
+#include <privilege-control.h>
+#endif
+#include <ace-dao-rw/AceDAO.h>
+#include <ace-dao-ro/AceDAOConversions.h>
+#include <ace/PolicyInformationPoint.h>
+#include <ace/PromptDecision.h>
+#include <dpl/log/log.h>
+#include <dpl/foreach.h>
+
+namespace {
+
+Request::ApplicationType getAppType(const Request *request) {
+    AceDB::AppTypes appType =
+        AceDB::AceDAOReadOnly::getWidgetType(request->getWidgetHandle());
+    switch (appType) {
+    case AceDB::AppTypes::Tizen:
+        LogDebug("==== Found Tizen application. ====");
+        return Request::APP_TYPE_TIZEN;
+    case AceDB::AppTypes::WAC20:
+        LogDebug("==== Found Wac20 application. ====");
+        return Request::APP_TYPE_WAC20;
+    default:
+        LogDebug("==== Unknown application type. ====");
+    }
+    return Request::APP_TYPE_UNKNOWN;
+}
+
+} // anonymous namespace
+
+void SecurityLogic::initialize() {
+    AceDB::AceDAO::attachToThreadRW();
+    m_policyEnforcementPoint.initialize(new WebRuntimeImpl(),
+                                        new ResourceInformationImpl(),
+                                        new OperationSystemImpl());
+}
+
+void SecurityLogic::terminate() {
+    m_policyEnforcementPoint.terminate();
+    AceDB::AceDAO::detachFromThread();
+}
+
+
+void SecurityLogic::grantPlatformAccess(const Request& request)
+{
+    (void)request;
+#ifdef WRT_SMACK_ENABLED
+    try {
+        unsigned long long id =
+            static_cast<unsigned long long>(request.getWidgetHandle());
+        Request::DeviceCapabilitySet dc = request.getDeviceCapabilitySet();
+
+        size_t i,size = dc.size();
+        std::unique_ptr<const char*[]> array(new const char*[size+1]);
+
+        array[size] = NULL;
+        auto it = dc.begin();
+
+        for(i=0; (i<size) && (it!=dc.end()); ++i,++it) {
+            array[i] = it->c_str();
+        }
+        int ret = wrt_permissions_add(id, array.get());
+        if (PC_OPERATION_SUCCESS != ret) {
+            LogError("smack rules couldn't be granted");
+        }
+    } catch (std::bad_alloc&) {
+        LogError("smack rules couldn't be granted: memory allocation failed");
+    }
+#endif
+}
+
+PolicyResult SecurityLogic::checkFunctionCall(Request* request)
+{
+    Assert(NULL != request);
+
+    LogDebug("=== Check widget existance ===");
+    Try {
+        request->setAppType(getAppType(request));
+    } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        LogError("==== Couldn't find widget for handle: " <<
+            request->getWidgetHandle() << ". Access denied. ====");
+        return PolicyEffect::DENY;
+    }
+
+    PolicyResult aceResult = m_policyEnforcementPoint.check(*request).policyResult;
+
+    if (aceResult == PolicyEffect::PERMIT) {
+        grantPlatformAccess(*request);
+        return PolicyEffect::PERMIT;
+    } else if (aceResult == PolicyEffect::PROMPT_ONESHOT ||
+               aceResult == PolicyEffect::PROMPT_SESSION ||
+               aceResult == PolicyEffect::PROMPT_BLANKET ||
+               aceResult == PolicyDecision::NOT_APPLICABLE ||
+               aceResult == PolicyResult::UNDETERMINED)
+    {
+        // TODO: check stored user answers!!!
+        // if necessary, grant SMACK rules
+        // return appropriately - the following is a dummy:
+        return aceResult;
+    } else {
+        return PolicyEffect::DENY;
+    }
+}
+
+PolicyResult SecurityLogic::checkFunctionCall(Request* request, const std::string &sessionId)
+{
+    Assert(NULL != request);
+    LogDebug("=== Check existance of widget === ");
+    Try {
+        request->setAppType(getAppType(request));
+    } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        LogError("==== Couldn't find widget for handle: " <<
+            request->getWidgetHandle() << ". Access denied. ====");
+        return PolicyEffect::DENY;
+    }
+
+    ExtendedPolicyResult exAceResult = m_policyEnforcementPoint.check(*request);
+    PolicyResult aceResult = exAceResult.policyResult;
+
+    LogDebug("Result returned by policy " << aceResult << ". RuleID: " << exAceResult.ruleId);
+
+    if (aceResult == PolicyEffect::PERMIT) {
+        LogDebug("Grant access.");
+        grantPlatformAccess(*request);
+        return PolicyEffect::PERMIT;
+    }
+
+    if (aceResult == PolicyEffect::PROMPT_ONESHOT ||
+        aceResult == PolicyEffect::DENY)
+    {
+        return aceResult;
+    }
+
+    OptionalCachedPromptDecision decision = AceDB::AceDAOReadOnly::getPromptDecision(
+        request->getWidgetHandle(),
+        exAceResult.ruleId);
+
+    if (!decision) {
+        LogDebug("No CachedPromptDecision found.");
+        return aceResult;
+    }
+
+    if (aceResult == PolicyEffect::PROMPT_BLANKET) {
+        if (decision->decision == PromptDecision::ALLOW_ALWAYS) {
+            LogDebug("Found user decision. Result changed to PERMIT. Access granted");
+            grantPlatformAccess(*request);
+            return PolicyEffect::PERMIT;
+        }
+        if (decision->decision == PromptDecision::DENY_ALWAYS) {
+            LogDebug("Found user decision. Result changed to DENY.");
+            return PolicyEffect::DENY;
+        }
+        if (decision->decision == PromptDecision::ALLOW_FOR_SESSION
+            && !!(decision->session)
+            && sessionId == DPL::ToUTF8String(*(decision->session)))
+        {
+            LogDebug("Result changed to PERMIT. Access granted.");
+            grantPlatformAccess(*request);
+            return PolicyEffect::PERMIT;
+        }
+        if (decision->decision == PromptDecision::DENY_FOR_SESSION
+            && !!(decision->session)
+            && sessionId == DPL::ToUTF8String(*(decision->session)))
+        {
+            LogDebug("Found user decision. Result changed to DENY.");
+            return PolicyEffect::DENY;
+        }
+        return aceResult;
+    }
+
+    if (aceResult == PolicyEffect::PROMPT_SESSION) {
+        if (decision->decision == PromptDecision::ALLOW_FOR_SESSION
+            && !!(decision->session)
+            && sessionId == DPL::ToUTF8String(*(decision->session)))
+        {
+            LogDebug("Found user decision. Result changed to PERMIT. Access granted.");
+            grantPlatformAccess(*request);
+            return PolicyEffect::PERMIT;
+        }
+        if (decision->decision == PromptDecision::DENY_FOR_SESSION
+            && !!(decision->session)
+            && sessionId == DPL::ToUTF8String(*(decision->session)))
+        {
+            LogDebug("Found user decision. Result changed to DENY.");
+            return PolicyEffect::DENY;
+        }
+        return aceResult;
+    }
+
+    // This should not happend - all PolicyEffect values were supported before.
+    // This mean that someone has modyfied PolicyEffect enum. SPANK SPANK SPANK
+    LogError("Unsupported PolicyEffect!");
+    return PolicyEffect::DENY;
+}
+
+void SecurityLogic::validatePopupResponse(Request* request,
+                                          bool allowed,
+                                          Prompt::Validity validity,
+                                          const std::string& sessionId,
+                                          bool* retValue)
+{
+    Assert(NULL != retValue);
+    Assert(NULL != request);
+
+    LogDebug("Start");
+    LogDebug("User answered: " << allowed << " with validity: " << validity);
+    LogDebug("Check widget existance");
+    Try {
+        request->setAppType(getAppType(request));
+    } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        LogError("==== Couldn't find widget for handle: " <<
+            request->getWidgetHandle() << ". Access denied. ====");
+        retValue = false;
+        return;
+    }
+
+    *retValue = false;
+    OptionalExtendedPolicyResult extendedAceResult =
+        m_policyEnforcementPoint.checkFromCache(*request);
+    if (!extendedAceResult) {
+        LogDebug("No cached policy result - but it should be here");
+        LogDebug("returning " << *retValue);
+        return;
+    }
+
+    PolicyResult aceResult = extendedAceResult->policyResult;
+    if (aceResult == PolicyEffect::DENY) {
+        LogDebug("returning " << *retValue);
+        return;
+    }
+    if (aceResult == PolicyEffect::PERMIT) {
+        // TODO  we were asked for prompt validation
+        // but we got that no prompt should be opened - is this OK?
+        // (this is on the diagram in wiki)
+        *retValue = true;
+    } else if (aceResult == PolicyEffect::PROMPT_ONESHOT ||
+               aceResult == PolicyEffect::PROMPT_SESSION ||
+               aceResult == PolicyEffect::PROMPT_BLANKET)
+    {
+        Request::DeviceCapabilitySet devCaps =
+                request->getDeviceCapabilitySet();
+
+        FOREACH (it, devCaps) {
+            Request::DeviceCapability resourceId = *it;
+            LogDebug("Recheck: " << *it);
+            // 1) check if per-widget settings permit
+            AceDB::PreferenceTypes wgtPref =
+                AceDB::AceDAOReadOnly::getWidgetDevCapSetting(
+                    resourceId,
+                    request->getWidgetHandle());
+            if (AceDB::PreferenceTypes::PREFERENCE_DENY == wgtPref) {
+                LogDebug("returning " << *retValue);
+                return;
+            }
+            // 2) check if per-dev-cap settings permit
+            AceDB::PreferenceTypes resPerf =
+                AceDB::AceDAOReadOnly::getDevCapSetting(resourceId);
+            if (AceDB::PreferenceTypes::PREFERENCE_DENY == resPerf) {
+                LogDebug("returning " << *retValue);
+                return;
+            }
+
+            // 3) check for stored propmt answer - should not be there
+            // TODO  - is this check necessary?
+            AceDB::BaseAttributeSet attributes;
+            AceDB::AceDAOReadOnly::getAttributes(&attributes);
+            Request req(request->getWidgetHandle(),
+                        request->getExecutionPhase());
+            req.addDeviceCapability(resourceId);
+            PolicyInformationPoint *pip =
+                m_policyEnforcementPoint.getPip();
+
+            Assert(NULL != pip);
+
+            pip->getAttributesValues(&req, &attributes);
+            auto attrHash = AceDB::AceDaoConversions::convertToHash(attributes);
+
+            // 4) validate consistency of answer with policy result
+            Prompt::Validity clampedValidity =
+                    clampPromptValidity(validity, *(aceResult.getEffect()));
+
+            // 5) store answer in database if appropriate
+            // TODO  how about userParam? sessionId?
+            DPL::String userParam = DPL::FromUTF8String(sessionId);
+            boost::optional<DPL::String> sessionOptional = DPL::FromUTF8String(sessionId);
+
+            switch (clampedValidity) {
+            case Prompt::Validity::ALWAYS: {
+                AceDB::AceDAO::setPromptDecision(
+                    request->getWidgetHandle(),
+                    extendedAceResult->ruleId,
+                    sessionOptional,
+                    allowed ?
+                    PromptDecision::ALLOW_ALWAYS :
+                    PromptDecision::DENY_ALWAYS);
+                break; }
+            case Prompt::Validity::SESSION: {
+                AceDB::AceDAO::setPromptDecision(
+                    request->getWidgetHandle(),
+                    extendedAceResult->ruleId,
+                    sessionOptional,
+                    allowed ?
+                    PromptDecision::ALLOW_FOR_SESSION :
+                    PromptDecision::DENY_FOR_SESSION);
+                break; }
+
+            case Prompt::Validity::ONCE: {
+                LogInfo("Validity ONCE, not saving prompt decision to cache");
+                break; }
+            }
+
+        }
+        // access granted!
+        *retValue = allowed;
+    }
+    if (*retValue) {
+        // 6) grant smack label if not granted yet
+        grantPlatformAccess(*request);
+    }
+    LogDebug("Finish");
+    LogDebug("returning " << *retValue);
+}
+
+void SecurityLogic::updatePolicy()
+{
+    LogDebug("SecurityLogic::updatePolicy");
+    m_policyEnforcementPoint.updatePolicy();
+}
+
+Prompt::Validity SecurityLogic::clampPromptValidity(
+        Prompt::Validity validity,
+        PolicyEffect effect)
+{
+    switch (effect) {
+    case PolicyEffect::PROMPT_BLANKET: {
+        return validity; }
+    case PolicyEffect::PROMPT_SESSION: {
+        if (Prompt::Validity::ALWAYS == validity) {
+            LogInfo("ALWAYS returned from prompt in PROMPT_SESSION");
+            return Prompt::Validity::SESSION;
+        }
+        return validity; }
+    case PolicyEffect::PROMPT_ONESHOT: {
+        if (Prompt::Validity::ONCE != validity) {
+            LogInfo("Not ONCE returned from prompt in PROMPT_ONESHOT");
+        }
+        return Prompt::Validity::ONCE; }
+    case PolicyEffect::DENY:
+    case PolicyEffect::PERMIT:
+    default: {// other options - should not happen
+        LogError("This kind of policy effect does not deal with prompts");
+        return Prompt::Validity::ONCE;  }
+    }
+}
+
diff --git a/src/services/ace/logic/security_logic.h b/src/services/ace/logic/security_logic.h
new file mode 100644 (file)
index 0000000..71f8bae
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This class simply redirects the access requests to access control engine.
+ * The aim is to hide access control engine specific details from WRT modules.
+ * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
+ * WRT specific and other information during the decision making.
+ *
+ * @file    security_controller.h
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @author  Piotr Kozbial (p.kozbial@samsung.com)
+ * @version 1.0
+ * @brief   Header file for security logic
+ */
+#ifndef SECURITY_LOGIC_H
+#define SECURITY_LOGIC_H
+
+#include <ace/Request.h>
+#include <ace/PolicyResult.h>
+#include <ace/AbstractPolicyEnforcementPoint.h>
+#include <ace/Preference.h>
+#include <ace/PolicyEnforcementPoint.h>
+#include <ace-dao-ro/PromptModel.h>
+
+/* SecurityLogic
+ * May only be created and used by SecurityController.
+ * There may be only one instance.
+ */
+class SecurityLogic {
+  public:
+    SecurityLogic() {}
+    ~SecurityLogic() {}
+    // initialize/terminate
+    /** */
+    void initialize();
+    /** */
+    void terminate();
+
+    /** */
+    PolicyResult checkFunctionCall(Request*);
+    PolicyResult checkFunctionCall(Request*, const std::string &session);
+
+    void validatePopupResponse(Request* request,
+                               bool allowed,
+                               Prompt::Validity validity,
+                               const std::string& sessionId,
+                               bool* retValue);
+
+    /**
+     * Updates policy and clears policy cache
+     */
+    void updatePolicy();
+
+  private:
+    PolicyEnforcementPoint m_policyEnforcementPoint;
+
+    Prompt::Validity clampPromptValidity(Prompt::Validity validity,
+                                         PolicyEffect effect);
+    void grantPlatformAccess(const Request& request);
+};
+
+#endif // SECURITY_CONTROLLER_H
diff --git a/src/services/ace/logic/simple_roaming_agent.cpp b/src/services/ace/logic/simple_roaming_agent.cpp
new file mode 100644 (file)
index 0000000..cb78c97
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    simple_roaming_agent.cpp
+ * @author  Pawel Sikorski (p.sikorski@samsung.com)
+ * @author  Lukasz Marek (l.marek@samsung.com)
+ * @author  Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version 1.0
+ * @brief   roaming agent
+ */
+
+#include "simple_roaming_agent.h"
+#include <vconf.h>
+#include <dpl/log/log.h>
+#include <dpl/singleton_impl.h>
+IMPLEMENT_SINGLETON(SimpleRoamingAgent)
+
+SimpleRoamingAgent::SimpleRoamingAgent()
+{
+    if (vconf_notify_key_changed(
+            VCONFKEY_TELEPHONY_SVC_ROAM,
+            vConfChagedCallback, this) < 0)
+    {
+        LogError("Cannot add vconf callback [" <<
+                 VCONFKEY_TELEPHONY_SVC_ROAM << "]");
+        Assert(false && "Cannot add vconf callback");
+    }
+
+    int result = 0;
+    if (vconf_get_int(VCONFKEY_TELEPHONY_SVC_ROAM, &result) != 0) {
+        LogError("Cannot get current roaming status");
+        Assert(false && "Cannot get current roaming status");
+    } else {
+        bool type = (result == VCONFKEY_TELEPHONY_SVC_ROAM_ON);
+        m_networkType = type ? ROAMING : HOME;
+        LogInfo("Network type is " << (type ? "ROAMING" : "HOME"));
+    }
+
+}
+
+SimpleRoamingAgent::~SimpleRoamingAgent()
+{
+    if (vconf_ignore_key_changed(
+            VCONFKEY_TELEPHONY_SVC_ROAM,
+            vConfChagedCallback) < 0)
+    {
+        LogError("Cannot rm vconf callback [" <<
+                 VCONFKEY_TELEPHONY_SVC_ROAM << "]");
+        //Assert(false && "Cannot remove vconf callback");
+    }
+
+}
+
+void SimpleRoamingAgent::vConfChagedCallback(keynode_t *keyNode, void *data)
+{
+    LogInfo("SimpleRoamingAgent::vConfChagedCallback ");
+    char *key = vconf_keynode_get_name(keyNode);
+
+    if (NULL == key) {
+        LogWarning("vconf key is null.");
+        return;
+    }
+    std::string keyString = key;
+    if (VCONFKEY_TELEPHONY_SVC_ROAM != keyString) {
+        LogError("Wrong key found");
+        Assert(false && "Wrong key found in vconf callback");
+        return;
+    }
+    SimpleRoamingAgent *agent = static_cast<SimpleRoamingAgent *>(data);
+    if (NULL == agent) {
+        LogError("Bad user arg from vconf lib");
+        Assert(false && "Bad user arg from vconf lib");
+        return;
+    }
+    int result = 0;
+    if (vconf_get_int(VCONFKEY_TELEPHONY_SVC_ROAM, &result) != 0) {
+        LogError("Cannot get current roaming status");
+        Assert(false && "Cannot get current roaming status");
+    } else {
+        bool type = (result == VCONFKEY_TELEPHONY_SVC_ROAM_ON);
+        agent->m_networkType = type ? ROAMING : HOME;
+        LogInfo("Network type is " << (type ? "ROAMING" : "HOME"));
+    }
+}
diff --git a/src/services/ace/logic/simple_roaming_agent.h b/src/services/ace/logic/simple_roaming_agent.h
new file mode 100755 (executable)
index 0000000..65b0bbe
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file    simple_roaming_agent.h
+ * @author  Pawel Sikorski (p.sikorski@samsung.com)
+ * @author  Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version 1.0
+ * @brief   simple roaming agent
+ */
+
+#ifndef WRT_SRC_ACCESS_CONTROL_COMMON_SIMPLE_ROAMING_AGENT_H_
+#define WRT_SRC_ACCESS_CONTROL_COMMON_SIMPLE_ROAMING_AGENT_H_
+
+#include <string>
+#include <dpl/singleton.h>
+#include <dpl/noncopyable.h>
+#include <vconf.h>
+
+class SimpleRoamingAgent : DPL::Noncopyable
+{
+  public:
+    bool IsRoamingOn() const
+    {
+        return ROAMING == m_networkType;
+    }
+
+  private:
+    enum NetworkType {ROAMING, HOME};
+
+    NetworkType m_networkType;
+
+    SimpleRoamingAgent();
+    virtual ~SimpleRoamingAgent();
+
+    static void vConfChagedCallback(keynode_t *keyNode, void *userParam);
+
+    friend class DPL::Singleton<SimpleRoamingAgent>;
+};
+
+typedef DPL::Singleton<SimpleRoamingAgent> SimpleRoamingAgentSingleton;
+
+#endif//WRT_SRC_ACCESS_CONTROL_COMMON_SIMPLE_ROAMING_AGENT_H_
diff --git a/src/services/ace/socket/ace_service_callbacks.cpp b/src/services/ace/socket/ace_service_callbacks.cpp
new file mode 100644 (file)
index 0000000..ac3f6cf
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_service_callbacks.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of Ace Service callbacks
+ */
+#include <string>
+#include <vector>
+#include <dpl/log/log.h>
+#include "ace_service_callbacks.h"
+#include <callback_api.h>
+#include <ace/Request.h>
+#include <ace/PolicyResult.h>
+#include <security_controller.h>
+#include <security_caller.h>
+#include <attribute_facade.h>
+
+namespace RPC {
+
+void AceServiceCallbacks::checkAccess(SocketConnection * connector){
+
+    int widgetHandle = 0;
+    std::string subject, resource, sessionId;
+    std::vector<std::string> paramNames, paramValues;
+    Try {
+        connector->read(&widgetHandle,
+                        &subject,
+                        &resource,
+                        &paramNames,
+                        &paramValues,
+                        &sessionId);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection read error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket Connection read error");
+    }
+
+    if (paramNames.size() != paramValues.size()) {
+        ThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException, "Varying sizes of parameter names and parameter values");
+    }
+    LogDebug("We got subject: " << subject);
+    LogDebug("We got resource: " << resource);
+
+    FunctionParamImpl params;
+    for (size_t i = 0; i < paramNames.size(); ++i) {
+        params.addAttribute(paramNames[i], paramValues[i]);
+    }
+
+    Request request(widgetHandle,
+                    WidgetExecutionPhase_Invoke,
+                    &params);
+    request.addDeviceCapability(resource);
+
+    PolicyResult result(PolicyEffect::DENY);
+    SecurityCallerSingleton::Instance().SendSyncEvent(
+        SecurityControllerEvents::CheckRuntimeCallSyncEvent(
+            &result,
+            &request,
+            sessionId));
+
+    int response = PolicyResult::serialize(result);
+
+    Try{
+        connector->write(response);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection write error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket Connection write error");
+    }
+}
+
+void AceServiceCallbacks::checkAccessInstall(SocketConnection * connector){
+
+    int widgetHandle;
+    std::string resource;
+
+    Try {
+        connector->read(&widgetHandle,
+                        &resource);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection read error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket Connection read error");
+    }
+
+    LogDebug("We got handle: " << widgetHandle);
+    LogDebug("We got resource: " << resource);
+
+    Request request(widgetHandle,
+          WidgetExecutionPhase_WidgetInstall);
+    request.addDeviceCapability(resource);
+
+    PolicyResult result(PolicyEffect::DENY);
+    SecurityCallerSingleton::Instance().SendSyncEvent(
+            SecurityControllerEvents::CheckFunctionCallSyncEvent(
+                    &result,
+                    &request));
+
+    int response = PolicyResult::serialize(result);
+
+    Try{
+        connector->write(response);
+    }  Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection write error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket Connection write error");
+    }
+}
+
+void AceServiceCallbacks::updatePolicy(SocketConnection * /*connector*/){
+
+
+    LogDebug("Policy update socket message received");
+    SecurityCallerSingleton::Instance().SendSyncEvent(
+            SecurityControllerEvents::UpdatePolicySyncEvent());
+}
+
+} //namespace RPC
diff --git a/src/services/ace/socket/ace_service_callbacks.h b/src/services/ace/socket/ace_service_callbacks.h
new file mode 100644 (file)
index 0000000..e5ebc18
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_service_callbacks.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of Ace Service callbacks
+ */
+
+#ifndef ACE_SERVICE_CALLBACKS_H_
+#define ACE_SERVICE_CALLBACKS_H_
+
+#include <memory>
+#include <SocketConnection.h>
+#include <dpl/log/log.h>
+
+namespace RPC {
+
+namespace AceServiceCallbacks {
+
+    // IN string subject
+    // IN string resource
+    // IN vector<string> function param names
+    // IN vector<string> function param values
+    // OUT int allow, deny, popup type
+    void checkAccess(SocketConnection * connector);
+
+    // IN string subject
+    // IN string resource
+    // OUT int allow, deny, popup type
+    void checkAccessInstall(SocketConnection * connector);
+
+    // Policy update trigger
+    void updatePolicy(SocketConnection * connector);
+
+};
+
+} //namespace RPC
+
+#endif /* ACE_SERVICE_CALLBACKS_H_ */
diff --git a/src/services/ace/socket/api/ace_service_callbacks_api.h b/src/services/ace/socket/api/ace_service_callbacks_api.h
new file mode 100644 (file)
index 0000000..dfd136b
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_service_callbacks_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header with api of implemented Ace Service callbacks
+ */
+#ifndef ACE_SERVICE_CALLBACKS_API_H_
+#define ACE_SERVICE_CALLBACKS_API_H_
+
+#include <string>
+#include <utility>
+#include "ace_server_api.h"
+#include "ace_service_callbacks.h"
+#include "callback_api.h"
+
+namespace WrtSecurity{
+namespace AceServiceCallbacksApi{
+
+inline const std::pair<std::string, socketServerCallback> CHECK_ACCESS_METHOD_CALLBACK() {
+    return std::make_pair(WrtSecurity::AceServerApi::CHECK_ACCESS_METHOD(),
+                          RPC::AceServiceCallbacks::checkAccess);
+}
+
+inline const std::pair<std::string, socketServerCallback> CHECK_ACCESS_INSTALL_METHOD_CALLBACK() {
+    return std::make_pair(WrtSecurity::AceServerApi::CHECK_ACCESS_INSTALL_METHOD(),
+                          RPC::AceServiceCallbacks::checkAccessInstall);
+}
+
+inline const std::pair<std::string, socketServerCallback> UPDATE_POLICY_METHOD_CALLBACK() {
+    return std::make_pair(WrtSecurity::AceServerApi::UPDATE_POLICY_METHOD(),
+                          RPC::AceServiceCallbacks::updatePolicy);
+}
+
+} // namespace AceServiceCallbacksApi
+} // namespace WrtSecurity
+
+
+#endif // ACE_SERVICE_CALLBACKS_API_H_
diff --git a/src/services/caller/security_caller.cpp b/src/services/caller/security_caller.cpp
new file mode 100644 (file)
index 0000000..8fab788
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        popup_service_callbacks.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of Security Caller Thread singleton
+ */
+
+#include <security_caller.h>
+#include <dpl/singleton_impl.h>
+
+IMPLEMENT_SINGLETON(SecurityCallerThread)
diff --git a/src/services/caller/security_caller.h b/src/services/caller/security_caller.h
new file mode 100644 (file)
index 0000000..e1b68d0
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        popup_service_callbacks.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       Header of Security Caller class used by services socket callbacks
+ */
+
+#ifndef SECURITY_CALLER_H__
+#define SECURITY_CALLER_H__
+
+#include <dpl/thread.h>
+#include <dpl/assert.h>
+#include <dpl/singleton.h>
+
+#include <security_controller.h>
+
+#include <pthread.h>
+
+class IEventHolder
+{
+ public:
+  virtual void FinalizeSending() = 0;
+  virtual ~IEventHolder() {};
+};
+
+template<class EventType>
+class EventHolderImpl : public IEventHolder
+{
+  EventType event;
+
+ public:
+  EventHolderImpl(const EventType& e) : event(e) {}
+  virtual void FinalizeSending()
+  {
+    LogDebug("sending real sync event");
+    CONTROLLER_POST_SYNC_EVENT(SecurityController, event);
+  }
+};
+
+/*
+ * Because Security Controller is a DPL::Controler class, its events
+ * can be send only from a DPL managed thread. SecurityCallerTread class
+ * has been implemented as a workaround of that constraint.
+ * This class is a DPL managed thread that waits for requests
+ * from non DPL managed threads and when receives one it posts event
+ * to the Security Controler in charge of the calling thread.
+ */
+
+
+class SecurityCallerThread : public DPL::Thread
+{
+ private:
+  pthread_mutex_t m_mutex2;
+  pthread_mutex_t m_mutex;
+  pthread_cond_t m_cond;
+  pthread_cond_t m_cond2;
+  bool m_continue;
+  bool m_finished;
+  IEventHolder* m_eventHolder;
+  pthread_mutex_t m_syncMutex;
+
+
+  SecurityCallerThread() :
+    Thread(),
+    m_mutex2(PTHREAD_MUTEX_INITIALIZER),
+    m_mutex(PTHREAD_MUTEX_INITIALIZER),
+    m_cond(PTHREAD_COND_INITIALIZER),
+    m_cond2(PTHREAD_COND_INITIALIZER),
+    m_continue(true),
+    m_finished(false),
+    m_eventHolder(NULL),
+    m_syncMutex(PTHREAD_MUTEX_INITIALIZER)
+  {
+    LogDebug("constructor");
+  }
+
+  virtual ~SecurityCallerThread()
+  {
+    pthread_mutex_unlock(&m_syncMutex);
+    pthread_cond_destroy(&m_cond);
+    pthread_cond_destroy(&m_cond2);
+    pthread_mutex_destroy(&m_mutex2);
+    pthread_mutex_destroy(&m_mutex);
+    pthread_mutex_destroy(&m_syncMutex);
+  }
+
+ protected:
+  /* main routine of the SecurityCallerThread */
+  virtual int ThreadEntry()
+  {
+    LogDebug("SecurityCallerThread start");
+    pthread_mutex_lock(&m_mutex); // lock shared data
+
+    while (m_continue) // main loop
+    {
+      if (m_eventHolder) // if m_eventHolder is set, the request has been received
+      {
+        m_eventHolder->FinalizeSending(); // send actual event in charge of calling thread
+        delete m_eventHolder;
+        m_eventHolder = NULL;
+        LogDebug("setting finished state");
+        pthread_mutex_lock(&m_syncMutex); // lock m_finished
+        m_finished = true;
+        pthread_mutex_unlock(&m_syncMutex); // unlock m_finished
+        LogDebug("finished");
+        pthread_cond_signal(&m_cond2); // signal a calling thread that event has been posted.
+      }
+      LogDebug("waiting for event");
+      // atomically:
+      // unlock m_mutex, wait on m_cond until signal received, lock m_mutex
+      pthread_cond_wait(&m_cond, &m_mutex);
+      LogDebug("found an event");
+    }
+
+    pthread_mutex_unlock(&m_mutex);
+
+    return 0;
+  }
+
+ public:
+  void Quit()
+  {
+    LogDebug("Quit called");
+    pthread_mutex_lock(&m_mutex);    // lock shared data
+    m_continue = false;              // main loop condition set to false
+    pthread_mutex_unlock(&m_mutex);  // unlock shard data
+    pthread_cond_signal(&m_cond);
+  }
+
+  template <class EventType>
+  void SendSyncEvent(const EventType& event)
+  {
+    // prevent SendSyncEvent being called by multiple threads at the same time.
+    pthread_mutex_lock(&m_mutex2);
+    LogDebug("sending sync event");
+    bool correct_thread = false;
+    Try {
+      LogDebug("Checking if this is unmanaged thread");
+      DPL::Thread::GetCurrentThread();
+    } Catch (DPL::Thread::Exception::UnmanagedThread) {
+      correct_thread = true;
+    }
+    Assert(correct_thread &&
+           "This method may not be called from DPL managed thread or main thread");
+    LogDebug("putting an event to be posted");
+    pthread_mutex_lock(&m_mutex);  // lock shared data
+    Assert(m_eventHolder == NULL && "Whooops");
+    m_eventHolder = new EventHolderImpl<EventType>(event); // put an event to be posted
+    pthread_mutex_unlock(&m_mutex); // unlock shared data
+    LogDebug("Signal caller thread that new event has been created");
+    pthread_cond_signal(&m_cond);   // signal SecurityCallerThread to wake up because new
+                                    // event is waiting to be posted
+
+    LogDebug("waiting untill send completes");
+    pthread_mutex_lock(&m_syncMutex); /* wait until send completes */
+    while (!m_finished)
+    {
+        pthread_cond_wait(&m_cond2, &m_syncMutex); // wait until event is posted
+    }
+    LogDebug("done");
+    m_finished = false;
+    pthread_mutex_unlock(&m_syncMutex);
+    pthread_mutex_unlock(&m_mutex2);
+  }
+
+ private:
+  friend class DPL::Singleton<SecurityCallerThread>;
+};
+
+typedef DPL::Singleton<SecurityCallerThread> SecurityCallerSingleton;
+
+
+
+#endif //SECURITY_CALLER_H__
diff --git a/src/services/ocsp/dbus/api/ocsp_server_dbus_api.h b/src/services/ocsp/dbus/api/ocsp_server_dbus_api.h
new file mode 100644 (file)
index 0000000..df9817b
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ocsp_server_api.h
+ * @author
+ * @version     1.0
+ * @brief       This file contains definitions OCSP server interface & methods specifically needed by DBus.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_API_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_API_H_
+
+#include "ocsp_server_api.h"
+#include<string>
+
+namespace WrtSecurity{
+namespace OcspServerApi{
+
+
+// RPC test function
+// IN std::string
+// OUT std::string
+inline const std::string ECHO_METHOD()
+{
+    return "echo";
+}
+
+
+
+}
+};
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_API_H_
diff --git a/src/services/ocsp/dbus/ocsp_server_dbus_interface.cpp b/src/services/ocsp/dbus/ocsp_server_dbus_interface.cpp
new file mode 100644 (file)
index 0000000..2acc5d8
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ocsp_service_dbus_interface.cpp
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of OCSP server API.
+ */
+#include "ocsp_server_dbus_interface.h"
+
+namespace RPC {
+
+using namespace WrtSecurity;
+
+OcspServerDBusInterface::OcspServerDBusInterface():
+    DPL::DBus::InterfaceDispatcher(OcspServerApi::INTERFACE_NAME())
+{
+    setXmlSignature("<node>"
+        "  <interface name='" + OcspServerApi::INTERFACE_NAME() + "'>"
+        "    <method name='" + OcspServerApi::ECHO_METHOD() + "'>"
+        "      <arg type='s' name='input' direction='in'/>"
+        "      <arg type='s' name='output' direction='out'/>"
+        "    </method>"
+        "    <method name='" + OcspServerApi::CHECK_ACCESS_METHOD() + "'>"
+        "      <arg type='i' name='input' direction='in'/>"
+        "      <arg type='i' name='output' direction='out'/>"
+        "    </method>"
+        "  </interface>"
+        "</node>");
+}
+
+
+void OcspServerDBusInterface::onMethodCall(
+        const gchar* argMethodName,
+        GVariant* argParameters,
+        GDBusMethodInvocation* argInvocation)
+{
+    if (OcspServerApi::ECHO_METHOD() == argMethodName){
+        // TODO: Deserialization should use
+        // DBus::SErverDeserialization::deserialize()
+        const gchar* arg = NULL;
+        g_variant_get(argParameters, "(&s)", &arg);
+        // TODO: Serialization should use
+        // DBus::SErverDeserialization::serialize()
+        gchar* response = g_strdup_printf(arg);
+        g_dbus_method_invocation_return_value(argInvocation,
+                                              g_variant_new ("(s)", response));
+        g_free (response);
+    } else if (OcspServerApi::CHECK_ACCESS_METHOD() == argMethodName) {
+        gint32 value;
+        g_variant_get(argParameters, "(i)", &value);
+
+        // TODO: this is making OCSP service a stub! this HAS to be moved
+        // with proper implementation to cert-svc daemon
+        gint32 response = 0; // Certificates are valid for now
+
+        GVariant* varResponse = g_variant_new ("(i)", response);
+                //This function will unref invocation and it will be freed
+        LogDebug("OCSP dbus interface tries to send result");
+        g_dbus_method_invocation_return_value(argInvocation, varResponse);
+    }
+}
+
+} // namespace RPC
diff --git a/src/services/ocsp/dbus/ocsp_server_dbus_interface.h b/src/services/ocsp/dbus/ocsp_server_dbus_interface.h
new file mode 100644 (file)
index 0000000..748c0bd
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ocsp_service_dbus_interface.h
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @version     1.0
+ * @brief       Class that handles OCSP server API.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_INTERFACE_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_INTERFACE_H_
+
+#include <list>
+#include <dpl/dbus/dbus_interface_dispatcher.h>
+#include "api/ocsp_server_dbus_api.h"
+
+namespace RPC {
+
+class OcspServerDBusInterface :
+    public DPL::DBus::InterfaceDispatcher
+{
+  public:
+    OcspServerDBusInterface();
+
+    virtual ~OcspServerDBusInterface()
+    {}
+
+    virtual void onMethodCall(const gchar* method_name,
+                              GVariant* parameters,
+                              GDBusMethodInvocation* invocation);
+};
+
+} // namespace RPC
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_INTERFACE_H_
diff --git a/src/services/ocsp/ocsp_server_api.h b/src/services/ocsp/ocsp_server_api.h
new file mode 100644 (file)
index 0000000..61be515
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ocsp_server_api.h
+ * @author
+ * @version     1.0
+ * @brief       This file contains definitions OCSP server interface & methods.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_API_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_API_H_
+
+#include "ocsp_server_api.h"
+#include<string>
+
+namespace WrtSecurity{
+namespace OcspServerApi{
+
+// DBus interface name
+inline const std::string INTERFACE_NAME()
+{
+    return "org.tizen.OcspCheck";
+}
+
+// Function checks WidgetStatus for installed widget.
+// https://106.116.37.24/wiki/WebRuntime/Security/Widget_Signatures
+// IN WidgetHandle Widget ID in Database
+// OUT WidgetStatus GOOD/REVOKED
+inline const std::string CHECK_ACCESS_METHOD()
+{
+    return "OcspCheck";
+}
+
+}
+};
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_API_H_
diff --git a/src/services/ocsp/ocsp_service.cpp b/src/services/ocsp/ocsp_service.cpp
new file mode 100644 (file)
index 0000000..34d3499
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        ocsp_service.cpp
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @version     1.0
+ * @brief       This is implementation file of Ocsp service
+ */
+
+#include "security_daemon.h"
+
+namespace OcspService {
+
+class OcspService : public SecurityDaemon::DaemonService
+{
+  private:
+    virtual void initialize()
+    {
+    }
+
+    virtual void start()
+    {
+    }
+
+    virtual void stop()
+    {
+    }
+
+    virtual void deinitialize()
+    {
+    }
+
+};
+
+DAEMON_REGISTER_SERVICE_MODULE(OcspService)
+
+}//namespace OcspService
+
diff --git a/src/services/ocsp/socket/api/ocsp_service_callbacks_api.h b/src/services/ocsp/socket/api/ocsp_service_callbacks_api.h
new file mode 100644 (file)
index 0000000..fd9bf3e
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ocsp_service_callbacks_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header with api of implemented Ocsp Service callbacks
+ */
+
+#ifndef OCSP_SERVICE_CALLBACKS_API_H_
+#define OCSP_SERVICE_CALLBACKS_API_H_
+
+#include <string>
+#include <utility>
+#include "SocketConnection.h"
+#include "ocsp_server_api.h"
+#include "ocsp_service_callbacks.h"
+#include "callback_api.h"
+
+namespace WrtSecurity{
+namespace OcspServiceCallbacksApi{
+
+inline const std::pair<std::string, socketServerCallback> CHECK_ACCESS_METHOD_CALLBACK(){
+    return std::make_pair(WrtSecurity::OcspServerApi::CHECK_ACCESS_METHOD(),
+                          RPC::OcspServiceCallbacks::checkAccess);
+}
+
+} // namespace OcspServiceCallbacksApi
+} // namespace WrtSecurity
+
+#endif // OCSP_SERVICE_CALLBACKS_API_H_
diff --git a/src/services/ocsp/socket/ocsp_service_callbacks.cpp b/src/services/ocsp/socket/ocsp_service_callbacks.cpp
new file mode 100644 (file)
index 0000000..53811b5
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ocsp_service_callbacks.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of Ocsp Service callbacks
+ */
+
+#include "ocsp_service_callbacks.h"
+#include <callback_api.h>
+#include <dpl/log/log.h>
+
+namespace RPC {
+
+void OcspServiceCallbacks::checkAccess(SocketConnection * connector){
+    int response = 0;
+    Try {
+        int handle;
+        connector->read(&handle);
+        LogDebug("handle : " << handle);
+        connector->write(response);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection write error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket Connection write error");
+    }
+}
+
+} // namespace RPC
diff --git a/src/services/ocsp/socket/ocsp_service_callbacks.h b/src/services/ocsp/socket/ocsp_service_callbacks.h
new file mode 100644 (file)
index 0000000..df77a80
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ocsp_service_callbacks.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of Ocsp Service callbacks class
+ */
+
+#ifndef OCSP_SERVICE_CALLBACKS_H_
+#define OCSP_SERVICE_CALLBACKS_H_
+
+#include <SocketConnection.h>
+
+namespace RPC {
+
+namespace OcspServiceCallbacks {
+    void checkAccess(SocketConnection * connector);
+};
+
+} // namespace RPC
+#endif /* OCSP_SERVICE_CALLBACKS_H_ */
diff --git a/src/services/popup/dbus/popup_response_dbus_interface.cpp b/src/services/popup/dbus/popup_response_dbus_interface.cpp
new file mode 100644 (file)
index 0000000..f897eeb
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file    popup_response_dispatcher.cpp
+ * @author  Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
+ * @version 1.0
+ * @brief
+ */
+
+#include "popup_response_dbus_interface.h"
+#include <vector>
+#include <string>
+#include <dpl/dbus/dbus_server_deserialization.h>
+#include <dpl/dbus/dbus_server_serialization.h>
+#include <ace/Request.h>
+#include <ace-dao-ro/PromptModel.h>
+#include "popup_ace_data_types.h"
+//#include "access-control/engine/PromptModel.h"
+#include "attribute_facade.h"
+//#include "Request.h"
+#include "security_controller.h"
+
+namespace RPC
+{
+
+void PopupResponseDBusInterface::onMethodCall(const gchar* methodName,
+                                           GVariant* parameters,
+                                           GDBusMethodInvocation* invocation)
+{
+    using namespace WrtSecurity;
+#if 1
+    if (0 == g_strcmp0(methodName,
+            PopupServerApi::VALIDATION_METHOD().c_str()))
+    {
+        // popup answer data
+        bool allowed = false;
+        int serializedValidity = 0;
+
+        // ACE data
+        AceUserdata acedata;
+
+        if (!DPL::DBus::ServerDeserialization::deserialize(
+                parameters,
+                &allowed,
+                &serializedValidity,
+                &(acedata.handle),
+                &(acedata.subject),
+                &(acedata.resource),
+                &(acedata.paramKeys),
+                &(acedata.paramValues),
+                &(acedata.sessionId)))
+        {
+            g_dbus_method_invocation_return_dbus_error(
+                          invocation,
+                          "org.tizen.PopupResponse.UnknownError",
+                          "Error in deserializing input parameters");
+            return;
+        }
+
+        if (acedata.paramKeys.size() != acedata.paramValues.size()) {
+            g_dbus_method_invocation_return_dbus_error(
+                      invocation,
+                      "org.tizen.PopupResponse.UnknownError",
+                      "Varying sizes of parameter names and parameter values");
+            return;
+        }
+
+        FunctionParamImpl params;
+        for (size_t i = 0; i < acedata.paramKeys.size(); ++i) {
+            params.addAttribute(acedata.paramKeys[i], acedata.paramValues[i]);
+        }
+        Request request(acedata.handle,
+                        WidgetExecutionPhase_Invoke,
+                        &params);
+        request.addDeviceCapability(acedata.resource);
+
+        Prompt::Validity validity = static_cast<Prompt::Validity>(serializedValidity);
+
+        bool response = false;
+        SecurityControllerEvents::ValidatePopupResponseEvent ev(
+            &request,
+            allowed,
+            validity,
+            acedata.sessionId,
+            &response);
+        CONTROLLER_POST_SYNC_EVENT(SecurityController, ev);
+
+        g_dbus_method_invocation_return_value(
+            invocation,
+            DPL::DBus::ServerSerialization::serialize(response));
+    }
+#endif
+}
+
+}
diff --git a/src/services/popup/dbus/popup_response_dbus_interface.h b/src/services/popup/dbus/popup_response_dbus_interface.h
new file mode 100644 (file)
index 0000000..19e9494
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file    popup_response_dbus_interface.h
+ * @author  Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
+ * @author  Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version 1.0
+ * @brief
+ */
+
+#ifndef WRT_SRC_RPC_DAEMON_POPUP_RESPONSE_DBUS_INTERFACE_H
+#define WRT_SRC_RPC_DAEMON_POPUP_RESPONSE_DBUS_INTERFACE_H
+
+#include <dpl/dbus/dbus_interface_dispatcher.h>
+#include "popup_response_server_api.h"
+
+namespace RPC {
+
+class PopupResponseDBusInterface : public DPL::DBus::InterfaceDispatcher
+{
+public:
+    PopupResponseDBusInterface():
+            DPL::DBus::InterfaceDispatcher(
+                    WrtSecurity::PopupServerApi::INTERFACE_NAME())
+    {
+        using namespace WrtSecurity;
+
+        setXmlSignature("<node>"
+                 "  <interface name='" +
+                         PopupServerApi::INTERFACE_NAME() + "'>"
+                 "    <method name='" +
+                         PopupServerApi::VALIDATION_METHOD() + "'>"
+                         // popup answer data
+                 "      <arg type='b' name='allowed' direction='in'/>"
+                 "      <arg type='i' name='valid' direction='in'/>"
+                         // this is copied from ace_server_dbus_interface
+                 "      <arg type='i' name='handle' direction='in'/>"
+                 "      <arg type='s' name='subject' direction='in'/>"
+                 "      <arg type='s' name='resource' direction='in'/>"
+                 "      <arg type='as' name='parameter names' direction='in'/>"
+                 "      <arg type='as' name='parameter values' direction='in'/>"
+                 "      <arg type='s' name='sessionId' direction='in'/>"
+                 "      <arg type='b' name='response' direction='out'/>"
+                 "    </method>"
+                 "  </interface>"
+                 "</node>");
+
+    }
+
+    virtual ~PopupResponseDBusInterface()
+    {}
+
+    virtual void onMethodCall(const gchar* methodName,
+                              GVariant* parameters,
+                              GDBusMethodInvocation* invocation);
+};
+
+}
+
+#endif // WRT_SRC_RPC_DAEMON_POPUP_RESPONSE_DBUS_INTERFACE_H
diff --git a/src/services/popup/popup_ace_data_types.h b/src/services/popup/popup_ace_data_types.h
new file mode 100644 (file)
index 0000000..1b5f734
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    popup_ace_data_types.h
+ * @author  Pawel Sikorski (p.sikorski@samsung.com)
+ * @version 1.0
+ * @brief
+ */
+
+#ifndef POPUP_ACE_DATA_TYPES_H_
+#define POPUP_ACE_DATA_TYPES_H_
+
+#include <vector>
+#include <string>
+
+// additional data needed by PolicyEvaluaor to recognize Popup Response
+struct AceUserdata
+{
+    //TODO INVALID_WIDGET_HANDLE is defined in wrt_plugin_export.h.
+    // I do not want to include that file here...
+    AceUserdata(): handle(-1) {}
+
+    int handle;
+    std::string subject;
+    std::string resource;
+    std::vector<std::string> paramKeys;
+    std::vector<std::string> paramValues;
+    std::string sessionId;
+};
+
+typedef bool SecurityStatus;
+
+#endif /* POPUP_ACE_DATA_TYPES_H_ */
diff --git a/src/services/popup/popup_response_server_api.h b/src/services/popup/popup_response_server_api.h
new file mode 100644 (file)
index 0000000..47dd4d3
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file    popup_response_server_api.h
+ * @author  Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
+ * @version 1.0
+ * @brief
+ */
+
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_API_POPUP_RESPONSE_SERVER_API_H
+#define WRT_SRC_RPC_SECURITY_DAEMON_API_POPUP_RESPONSE_SERVER_API_H
+
+#include <string>
+
+namespace WrtSecurity{
+namespace PopupServerApi{
+
+inline const std::string INTERFACE_NAME()
+{
+    return "org.tizen.PopupResponse";
+}
+
+inline const std::string VALIDATION_METHOD()
+{
+    return "validate";
+}
+
+}
+}
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_API_POPUP_RESPONSE_SERVER_API_H
+
diff --git a/src/services/popup/socket/api/popup_service_callbacks_api.h b/src/services/popup/socket/api/popup_service_callbacks_api.h
new file mode 100644 (file)
index 0000000..d22b9c7
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        popup_service_callbacks_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header with api of Popup Service callbacks
+ */
+
+#ifndef POPUP_SERVICE_CALLBACKS_API_H_
+#define POPUP_SERVICE_CALLBACKS_API_H_
+
+#include <string>
+#include <utility>
+#include "SocketConnection.h"
+#include "popup_response_server_api.h"
+#include "popup_service_callbacks.h"
+#include <callback_api.h>
+
+namespace WrtSecurity{
+namespace PopupServiceCallbacksApi{
+
+inline std::pair<std::string, socketServerCallback> VALIDATION_METHOD_CALLBACK(){
+    return std::make_pair(WrtSecurity::PopupServerApi::VALIDATION_METHOD(), RPC::PopupServiceCallbacks::validate);
+}
+
+} // namespace PopupServiceCallbacksApi
+} // namespace WrtSecurity
+
+#endif /* POPUP_SERVICE_CALLBACKS_API_H_ */
diff --git a/src/services/popup/socket/popup_service_callbacks.cpp b/src/services/popup/socket/popup_service_callbacks.cpp
new file mode 100644 (file)
index 0000000..d3e88e0
--- /dev/null
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        popup_service_callbacks.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of Popup Service callbacks
+ */
+
+#include "popup_service_callbacks.h"
+#include <callback_api.h>
+#include <ace/Request.h>
+#include <ace-dao-ro/PromptModel.h>
+#include <dpl/log/log.h>
+#include "attribute_facade.h"
+#include "popup_ace_data_types.h"
+#include "security_controller.h"
+#include <security_caller.h>
+
+namespace RPC {
+
+void PopupServiceCallbacks::validate(SocketConnection * connector){
+
+    bool allowed = false;
+    int serializedValidity = 0;
+
+    AceUserdata acedata;
+
+    Try {
+        connector->read(&allowed,
+                        &serializedValidity,
+                        &(acedata.handle),
+                        &(acedata.subject),
+                        &(acedata.resource),
+                        &(acedata.paramKeys),
+                        &(acedata.paramValues),
+                        &(acedata.sessionId));
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket connection read error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket connection read error");
+    }
+
+    if (acedata.paramKeys.size() != acedata.paramValues.size()) {
+        ThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                 "Varying sizes of parameter names vector and parameter values vector");
+    }
+    FunctionParamImpl params;
+    for (size_t i = 0; i < acedata.paramKeys.size(); ++i) {
+        params.addAttribute(acedata.paramKeys[i], acedata.paramValues[i]);
+    }
+    Request request(acedata.handle,
+                    WidgetExecutionPhase_Invoke,
+                    &params);
+    request.addDeviceCapability(acedata.resource);
+
+    Prompt::Validity validity = static_cast<Prompt::Validity>(serializedValidity);
+
+    bool response = false;
+    SecurityControllerEvents::ValidatePopupResponseEvent ev(
+        &request,
+        allowed,
+        validity,
+        acedata.sessionId,
+        &response);
+    SecurityCallerSingleton::Instance().SendSyncEvent(ev);
+
+    Try {
+        connector->write(response);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket connection write error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket connection write error");
+    }
+}
+
+} // namespace RPC
diff --git a/src/services/popup/socket/popup_service_callbacks.h b/src/services/popup/socket/popup_service_callbacks.h
new file mode 100644 (file)
index 0000000..e7d30f2
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        popup_service_callbacks.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of Popup Service callbacks
+ */
+
+#ifndef POPUP_SERVICE_CALLBACKS_H_
+#define POPUP_SERVICE_CALLBACKS_H_
+
+#include <memory>
+#include <SocketConnection.h>
+
+namespace RPC {
+
+namespace PopupServiceCallbacks {
+    void validate(SocketConnection * connector);
+};
+
+} // namespace RPC
+#endif /* POPUP_SERVICE_CALLBACKS_H_ */
diff --git a/systemd/wrt-security-daemon.service b/systemd/wrt-security-daemon.service
new file mode 100644 (file)
index 0000000..96e140d
--- /dev/null
@@ -0,0 +1,13 @@
+
+[Unit]
+Description=Wrt security daemon
+Requires=wrt-security-daemon.socket
+
+[Service]
+Type=notify
+ExecStart=/usr/bin/wrt-security-daemon
+Restart=always
+RestartSec=0
+
+[Install]
+WantedBy=multi-user.target
diff --git a/systemd/wrt-security-daemon.socket b/systemd/wrt-security-daemon.socket
new file mode 100644 (file)
index 0000000..d5aa41f
--- /dev/null
@@ -0,0 +1,10 @@
+[Unit]
+Description=Wrt Security socket
+
+[Socket]
+ListenStream=/tmp/server
+SocketMode=0777
+PassCredentials=yes
+Accept=false
+SmackLabelIPIn=wrt-security-daemon
+SmackLabelIPOut=wrt-security-daemon
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
new file mode 100644 (file)
index 0000000..9323584
--- /dev/null
@@ -0,0 +1,44 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+
+ADD_SUBDIRECTORY(security_daemon_tests)
+ADD_SUBDIRECTORY(ace)
+ADD_SUBDIRECTORY(ace_client)
+ADD_SUBDIRECTORY(ace_install)
+ADD_SUBDIRECTORY(ace_settings)
+ADD_SUBDIRECTORY(geolocation_security)
+ADD_SUBDIRECTORY(smack_security)
+
+INSTALL(FILES ${PROJECT_SOURCE_DIR}/tests/wrt-tests-security-all.sh
+    DESTINATION bin
+    PERMISSIONS OWNER_READ
+                OWNER_WRITE
+                OWNER_EXECUTE
+                GROUP_READ
+                GROUP_EXECUTE
+                WORLD_READ
+                WORLD_EXECUTE
+    )
+
+INSTALL(FILES ${PROJECT_SOURCE_DIR}/tests/security-tests.sh
+    DESTINATION bin
+    PERMISSIONS OWNER_READ
+                OWNER_WRITE
+                OWNER_EXECUTE
+                GROUP_READ
+                GROUP_EXECUTE
+                WORLD_READ
+                WORLD_EXECUTE
+    )
diff --git a/tests/ace/AttributeSetter.cpp b/tests/ace/AttributeSetter.cpp
new file mode 100644 (file)
index 0000000..18a31f0
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#include "AttributeSetter.h"
+
+#include <dpl/singleton_impl.h>
+IMPLEMENT_SINGLETON(AttributeSetter)
diff --git a/tests/ace/AttributeSetter.h b/tests/ace/AttributeSetter.h
new file mode 100644 (file)
index 0000000..a17b1ee
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file    AttributeSetter.h
+ * @author  Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version 0.1
+ * @brief   Stub for attribute_facade.h
+ */
+#ifndef _TEST_ACE_TESTS_ATTRIBUTE_SETTER_
+#define _TEST_ACE_TESTS_ATTRIBUTE_SETTER_
+
+#include <list>
+#include <map>
+#include <string>
+
+#include <dpl/singleton.h>
+#include <dpl/foreach.h>
+#include <dpl/log/log.h>
+
+#include <ace/Request.h>
+#include <ace/WRT_INTERFACE.h>
+
+class AttributeSetter {
+public:
+    typedef std::list<std::string> ValueList;
+    typedef std::map<std::string, ValueList> AttributeMap;
+    typedef std::map<int, AttributeMap> CollectionHandlerMap;
+
+    typedef std::list<ATTRIBUTE> Evil;
+
+    void get(const Request &request,
+            const Evil* evil)
+    {
+        int handle = request.getWidgetHandle();
+
+        CollectionHandlerMap::iterator widgetContextIt =
+            m_collectionMap.find(handle);
+
+        if (widgetContextIt == m_collectionMap.end()) {
+            LogError("WidgetContext is empty");
+            return;
+        }
+
+        FOREACH(it, *evil)
+        {
+            std::string attrName = *(it->first);
+
+            if (attrName == "device-cap") {
+                Request::DeviceCapabilitySet devCapSet =
+                    request.getDeviceCapabilitySet();
+                std::copy(devCapSet.begin(),
+                          devCapSet.end(),
+                          std::back_inserter(*(it->second)));
+                continue;
+            }
+
+            AttributeMap::iterator attrIt =
+                widgetContextIt->second.find(attrName);
+
+            if (attrIt == widgetContextIt->second.end()) {
+                LogError("No attribute: " << attrName <<
+                    " in context nr: " << handle);
+                const ATTRIBUTE &a = *it;
+                const_cast<ATTRIBUTE&>(a).second = NULL;
+                continue;
+            }
+
+            ValueList valueList = attrIt->second;
+
+            std::copy(valueList.begin(),
+                      valueList.end(),
+                      std::back_inserter(*(it->second)));
+        }
+    }
+
+    void addValue(int handler,
+                  const std::string &attributeName,
+                  const std::string &attributeValue)
+    {
+        m_collectionMap[handler][attributeName].push_back(attributeValue);
+    }
+
+    std::string getValue(int handler, const std::string &attributeName)
+    {
+        std::list<std::string> lst = m_collectionMap[handler][attributeName];
+        if (lst.empty())
+            return "fake-device-name-that-should-not-match-with-anything";
+        return lst.front();
+    }
+
+    void addValue(int handler,
+                  const char *attributeName,
+                  const char *attributeValue)
+    {
+        std::string aN = attributeName;
+        std::string aV = attributeValue;
+        addValue(handler, aN, aV);
+    }
+
+    void clear() {
+        m_collectionMap.clear();
+    }
+protected:
+    AttributeSetter(){}
+    ~AttributeSetter(){}
+private:
+    CollectionHandlerMap m_collectionMap;
+};
+
+typedef DPL::Singleton<AttributeSetter> AttributeSetterSingleton;
+
+#endif // _TEST_ACE_TESTS_ATTRIBUTE_SETTER_
diff --git a/tests/ace/CMakeLists.txt b/tests/ace/CMakeLists.txt
new file mode 100644 (file)
index 0000000..0be8f36
--- /dev/null
@@ -0,0 +1,73 @@
+#
+#Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an "AS IS" BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+# @version     0.1
+# @brief
+#
+INCLUDE(FindPkgConfig)
+SET(TARGET_ACE_TEST "wrt-tests-ace")
+
+PKG_CHECK_MODULES(ACE_TEST_DEP
+    libxml-2.0
+    dpl-test-efl
+    dpl-utils-efl
+    dpl-db-efl
+    gobject-2.0
+    REQUIRED
+    )
+
+# Set DPL tests sources
+SET(ACE_TESTS_SOURCES
+    ${PROJECT_SOURCE_DIR}/tests/ace/ace_tests.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace/loop_control.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace/TestSuite01.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace/TestSuite02.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace/TestSuite03.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace/TestSuite04.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace/TestSuite05.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace/TestSuite06.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace/Interfaces.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace/PEPSingleton.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace/AttributeSetter.cpp
+    )
+
+INCLUDE_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/src/services/ace
+    ${PROJECT_SOURCE_DIR}/ace/include
+    ${PROJECT_SOURCE_DIR}/tests/ace
+    ${ACE_TEST_DEP_INCLUDE_DIRS}
+    )
+
+ADD_EXECUTABLE(${TARGET_ACE_TEST} ${ACE_TESTS_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_ACE_TEST}
+    ${TARGET_ACE_LIB}
+    ${ACE_TEST_DEP_LIBRARIES}
+    )
+
+INSTALL(TARGETS ${TARGET_ACE_TEST}
+    DESTINATION bin
+    PERMISSIONS OWNER_READ
+                OWNER_WRITE
+                OWNER_EXECUTE
+                GROUP_READ
+                GROUP_EXECUTE
+                WORLD_READ
+                WORLD_EXECUTE
+    )
+
+ADD_SUBDIRECTORY(test-configuration)
diff --git a/tests/ace/Interfaces.cpp b/tests/ace/Interfaces.cpp
new file mode 100644 (file)
index 0000000..78ed1d0
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        Interfaces.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Stubs used by PolicyInformationPoint.h
+ */
+#include "Interfaces.h"
+
+#include <dpl/log/log.h>
+
+#include "AttributeSetter.h"
+
+int WebRuntimeImp::getAttributesValues(
+        const Request &request,
+        std::list<ATTRIBUTE> *attribute)
+{
+    LogError("Running stub");
+    AttributeSetterSingleton::Instance().get(request, attribute);
+    return 0;
+}
+
+int ResourceInformationImp::getAttributesValues(
+        const Request &request,
+        std::list<ATTRIBUTE> *attribute)
+{
+    LogError("Running stub");
+    AttributeSetterSingleton::Instance().get(request, attribute);
+    return 0;
+}
+
+int OperationSystemImp::getAttributesValues(
+        const Request &request,
+        std::list<ATTRIBUTE> *attribute)
+{
+    LogError("Running stub");
+    AttributeSetterSingleton::Instance().get(request, attribute);
+    return 0;
+}
+
+int FunctionParamImpl::getAttributesValues(const Request & /* request*/,
+        std::list<ATTRIBUTE> *attributes)
+{
+    LogError("Running stub");
+    FOREACH(iter, *attributes)
+    {
+        std::string attributeName = *(iter->first);
+
+        ParamMap::const_iterator i;
+        std::pair<ParamMap::const_iterator, ParamMap::const_iterator> jj =
+          paramMap.equal_range(attributeName);
+
+        for (i = jj.first; i != jj.second; ++i) {
+            iter->second->push_back(i->second);
+            LogDebug("Attribute: " << attributeName << " Value: " <<
+              i->second);
+        }
+    }
+    return 0;
+}
+
diff --git a/tests/ace/Interfaces.h b/tests/ace/Interfaces.h
new file mode 100644 (file)
index 0000000..3ea36d4
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        Interfaces.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Stubs used by PolicyInformationPoint.h
+ */
+#ifndef _TEST_ACE_TESTS_INTERFACE_H_
+#define _TEST_ACE_TESTS_INTERFACE_H_
+
+#include <string>
+#include <ace/WRT_INTERFACE.h>
+#include <map>
+#include <vector>
+
+class Request;
+
+class WebRuntimeImp : public IWebRuntime {
+public:
+    int getAttributesValues(
+            const Request &request,
+            std::list<ATTRIBUTE> *attribute);
+    std::string getSessionId(const Request &) { return std::string(); }
+};
+
+class ResourceInformationImp : public IResourceInformation {
+public:
+    int getAttributesValues(
+            const Request &request,
+            std::list<ATTRIBUTE> *attribute);
+};
+
+class OperationSystemImp : public IOperationSystem {
+public:
+    int getAttributesValues(
+            const Request &request,
+            std::list<ATTRIBUTE> *attribute);
+};
+
+class FunctionParamImpl : public IFunctionParam
+{
+public:
+    virtual int getAttributesValues(const Request & /* request*/,
+      std::list<ATTRIBUTE> *attributes);
+    void addAttribute(const std::string &key,
+      const std::string &value)
+    {
+        paramMap.insert(make_pair(key, value));
+    }
+    virtual ~FunctionParamImpl() {}
+private:
+    typedef std::multimap<std::string, std::string> ParamMap;
+    ParamMap paramMap;
+};
+
+#endif //  _TEST_ACE_TESTS_INTERFACE_H_
diff --git a/tests/ace/PEPSingleton.cpp b/tests/ace/PEPSingleton.cpp
new file mode 100644 (file)
index 0000000..9551700
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        Interfaces.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Instance of PEP used in tests.
+ */
+#include "PEPSingleton.h"
+
+#include <dpl/singleton_impl.h>
+IMPLEMENT_SINGLETON(PolicyEnforcementPoint)
+
diff --git a/tests/ace/PEPSingleton.h b/tests/ace/PEPSingleton.h
new file mode 100644 (file)
index 0000000..97c71d8
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        Interfaces.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Instantion of PEP used in tests.
+ */
+#ifndef _TEST_ACE_TEST_PEPSINGLETON_H_
+#define _TEST_ACE_TEST_PEPSINGLETON_H_
+
+#include <dpl/singleton.h>
+#include <ace/PolicyEnforcementPoint.h>
+
+typedef DPL::Singleton<PolicyEnforcementPoint> PEPSingleton;
+
+#endif // _TEST_ACE_TEST_PEPSINGLETON_H_
+
diff --git a/tests/ace/TestSuite01.cpp b/tests/ace/TestSuite01.cpp
new file mode 100644 (file)
index 0000000..3c11f43
--- /dev/null
@@ -0,0 +1,1661 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    TestSuite01.cpp
+ * @author  unknown
+ * @version 1.0
+ * @brief   Test cases for PolicyEvaluator class.
+ */
+#include <string>
+
+#include <dpl/log/log.h>
+#include <dpl/test/test_runner.h>
+
+#include <ace-dao-rw/AceDAO.h>
+#include <ace-dao-ro/AppTypes.h>
+#include <ace/Preference.h>
+#include <ace/SettingsLogic.h>
+#include <ace/PolicyEvaluator.h>
+
+#include "AttributeSetter.h"
+#include "Interfaces.h"
+#include "PEPSingleton.h"
+#include "widget_installer.h"
+
+#define GENERAL_TEST_POLICY "/usr/etc/ace/general-test.xml"
+#define GENERAL_TEST_POLICY_UNDETERMIND "/usr/etc/ace/undefined-test.xml"
+#define GENERAL_TEST_POLICY_GSETTINGS "/usr/etc/ace/policy-test-gsettings.xml"
+#define GENERAL_TEST_POLICY_TEST "/usr/etc/ace/policy-test.xml"
+
+#define CLEANENV(d)                                                         \
+    do{                                                                     \
+        if (PEPSingleton::Instance().getPdp()->getCurrentPolicy() != (d)) { \
+            PEPSingleton::Instance().getPdp()->updatePolicy(d);             \
+        }                                                                   \
+        AttributeSetterSingleton::Instance().clear();                       \
+        AceDB::AceDAO::clearWidgetDevCapSettings();                         \
+        AceDB::AceDAO::clearDevCapSettings();                               \
+    }while(0)
+
+// new version for many policies support from known locations
+#define CLEANENV_KNOWN_POLICY_LOCATIONS                                     \
+     do{                                                                    \
+        PEPSingleton::Instance().getPdp()->updatePolicy();                  \
+        AttributeSetterSingleton::Instance().clear();                       \
+        AceDB::AceDAO::clearWidgetDevCapSettings();                         \
+        AceDB::AceDAO::clearDevCapSettings();                               \
+    }while(0)
+
+/* QUery */
+#define QU(nr, subid, resid)                                                        \
+    do{                                                                             \
+        AttributeSetterSingleton::Instance().addValue((nr), "id", (subid));         \
+        AttributeSetterSingleton::Instance().addValue((nr), "resource-id", (resid));\
+    }while(0)
+
+/* Query Attribute */
+#define QA(nr, attrname, attrvalue) \
+    AttributeSetterSingleton::Instance().addValue((nr), (attrname), (attrvalue))
+
+/* Query Call */
+#define QC(nr, expect)                                                         \
+    do{                                                                        \
+        Request request((nr), WidgetExecutionPhase_Unknown);                   \
+        request.setAppType(Request::APP_TYPE_WAC20);                           \
+        std::string a =                                                        \
+            AttributeSetterSingleton::Instance().getValue((nr),"resource-id"); \
+        request.addDeviceCapability(a);                                        \
+        ExtendedPolicyResult result = PEPSingleton::Instance().check(request); \
+        RUNNER_ASSERT(result.policyResult == (expect));                        \
+    }while(0)
+
+/* Query Tizen Call */
+#define QTC(nr, expect)                                                        \
+    do{                                                                        \
+        Request request((nr), WidgetExecutionPhase_Unknown);                   \
+        request.setAppType(Request::APP_TYPE_TIZEN);                           \
+        std::string a =                                                        \
+            AttributeSetterSingleton::Instance().getValue((nr),"resource-id"); \
+        request.addDeviceCapability(a);                                        \
+        ExtendedPolicyResult result = PEPSingleton::Instance().check(request); \
+        RUNNER_ASSERT(result.policyResult == (expect));                        \
+    }while(0)
+
+/* Query Call with Param */
+#define QCP(nr, param, expect)                                                 \
+    do{                                                                        \
+        Request request((nr), WidgetExecutionPhase_Unknown, (param));          \
+        request.setAppType(Request::APP_TYPE_WAC20);                           \
+        std::string a =                                                        \
+            AttributeSetterSingleton::Instance().getValue((nr),"resource-id"); \
+        request.addDeviceCapability(a);                                        \
+        ExtendedPolicyResult result = PEPSingleton::Instance().check(request); \
+        RUNNER_ASSERT(result.policyResult == (expect));                        \
+    }while(0)
+
+#define TESTSUITE01(n) \
+RUNNER_TEST(ts01_general_tests_ ## n)
+
+RUNNER_TEST_GROUP_INIT(ACE_TEST_SUITE_01)
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and default condition "and" for resource and version
+ * expect: Permit
+ */
+TESTSUITE01(01){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "subject", "resource");
+    QA(1, "version", "3");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+ /*
+  * author:
+  * test: ACE Engine
+  * description: Tested algorithm "first-matching-target" for resource
+  * expect: Deny
+  */
+TESTSUITE01(02){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(2, "subject2", "resource");
+    QA(2, "version", "1");
+    QC(2, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target" and "deny-overrides" (as policy-set default value)
+ * expect: Deny
+ */
+TESTSUITE01(03){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(3, "subject3", "resource2");
+    QC(3, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target" and "deny-overrides" (as <policy-set> default value)
+ * expect: Permit
+ */
+TESTSUITE01(04){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(4, "subject4", "resource4");
+    QA(4, "version", "4");
+    QC(4, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and "and" & "or" conditions
+ * expect: Permit, Not Applicable, Permit
+ */
+TESTSUITE01(05){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(5, "subject5", "resource5");
+    QA(5, "version", "5");
+    QC(5, PolicyEffect::PERMIT);
+
+    QU(6, "subject5", "resource5");
+    QA(6, "version", "1");
+    QC(6, PolicyDecision::NOT_APPLICABLE);
+
+    QU(7, "subject6", "resource6");
+    QA(7, "version", "1");
+    QC(7, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "deny-overrides", and "and" & "or" conditions
+ * expect: Not applicable, Permit
+ */
+TESTSUITE01(06){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(6, "subject7", "resource7");
+    QA(6, "version", "7");
+    QA(6, "author", "author");
+    QC(6, PolicyDecision::NOT_APPLICABLE);
+
+    QU(7, "subject7", "resource7");
+    QA(7, "version", "7");
+    QA(7, "author", "author2");
+    QC(7, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "deny-overrides", and logical conditions
+ * expect: Deny
+ */
+TESTSUITE01(07){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(3, "subject7", "resource7");
+    QA(3, "version", "1");
+    QA(3, "author", "author3");
+    QC(3, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target" with one condition (Policy-4-5-6)
+ * expect: Permit, Deny, Not applicable
+ */
+TESTSUITE01(08){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(8, "s8a", "r8");
+    QA(8, "r8v1", "1");
+    QA(8, "r8v2", "2");
+    QC(8, PolicyEffect::PERMIT);
+
+    QU(9, "s8b", "r8");
+    QA(9, "r8v1", "1");
+    QA(9, "r8v2", "2");
+    QC(9, PolicyEffect::DENY);
+
+    QU(19, "s8c", "r8");
+    QA(19, "r8v1", "1");
+    QA(19, "r8v2", "2");
+    QC(19, PolicyDecision::NOT_APPLICABLE);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-applicable" and matching resource (Policy-7-14)
+ * expect:
+ */
+TESTSUITE01(09){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s9a", "r9");
+    QA(1, "r9a", "http://onet.pl:90/test.html");
+    QA(1, "r9b", "http://onet.pl:80/test.html");
+    QA(1, "r9c", "http://onet.pl:80");
+    QA(1, "r9d", "http://onet.pl:80");
+    QA(1, "r9e", "http://onet.pl:80/test.html");
+    QA(1, "r9g", "http://onet.pl:80/test.html");
+    QC(1, PolicyEffect::PERMIT);
+
+    QU(2, "s9b", "r9");
+    QA(2, "r9a", "http://onet.pl:90/test.html");
+    QA(2, "r9b", "http://onet.pl:80/test.html");
+    QA(2, "r9c", "http://onet.pl:80");
+    QA(2, "r9d", "http://onet.pl:80");
+    QA(2, "r9e", "http://onet.pl:80/test.html");
+    QA(2, "r9g", "http://onet.pl:80/test.html");
+    QC(2, PolicyEffect::DENY);
+
+    QU(3, "s9c", "r9");
+    QA(3, "r9a", "http://onet.pl:90/test.html");
+    QA(3, "r9b", "http://onet.pl:80/test.html");
+    QA(3, "r9c", "http://onet.pl:80");
+    QA(3, "r9d", "http://onet.pl:80");
+    QA(3, "r9e", "http://onet.pl:80/test.html");
+    QA(3, "r9g", "http://onet.pl:80/test.html");
+    QC(3, PolicyEffect::PERMIT);
+
+    QU(4, "s9d", "r9");
+    QA(4, "r9a", "http://onet.pl:90/test.html");
+    QA(4, "r9b", "http://onet.pl:80/test.html");
+    QA(4, "r9c", "http://onet.pl:80");
+    QA(4, "r9d", "http://onet.pl:80");
+    QA(4, "r9e", "http://onet.pl:80/test.html");
+    QA(4, "r9g", "http://onet.pl:80/test.html");
+    QC(4, PolicyEffect::DENY);
+
+    QU(5, "s9e", "r9");
+    QA(5, "r9a", "http://onet.pl:90/test.html");
+    QA(5, "r9b", "http://onet.pl:80/test.html");
+    QA(5, "r9c", "http://onet.pl:80");
+    QA(5, "r9d", "http://onet.pl:80");
+    QA(5, "r9e", "http://onet.pl:80/test.html");
+    QA(5, "r9g", "http://onet.pl:80/test.html");
+    QC(5, PolicyEffect::DENY);
+
+    QU(6, "s9f", "r9");
+    QA(6, "r9a", "http://onet.pl:90/test.html");
+    QA(6, "r9b", "http://onet.pl:80/test.html");
+    QA(6, "r9c", "http://onet.pl:80");
+    QA(6, "r9d", "http://onet.pl:80");
+    QA(6, "r9e", "http://onet.pl:80/test.html");
+    QA(6, "r9g", "http://onet.pl:80/test.html");
+    QC(6, PolicyEffect::PERMIT);
+
+    QU(7, "s9g", "r9");
+    QA(7, "r9a", "http://onet.pl:90/test.html");
+    QA(7, "r9b", "http://onet.pl:80/test.html");
+    QA(7, "r9c", "http://onet.pl:80");
+    QA(7, "r9d", "http://onet.pl:80");
+    QA(7, "r9e", "http://onet.pl:80/test.html");
+    QA(7, "r9g", "http://onet.pl:80/test.html");
+    QC(7, PolicyEffect::DENY);
+
+    QU(8, "s9h", "r9");
+    QA(8, "r9a", "http://onet.pl:90/test.html");
+    QA(8, "r9b", "http://onet.pl:80/test.html");
+    QA(8, "r9c", "http://onet.pl:80");
+    QA(8, "r9d", "http://onet.pl:80");
+    QA(8, "r9e", "http://onet.pl:80/test.html");
+    QA(8, "r9g", "http://onet.pl:80/test.html");
+    QC(8, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-applicable", matching function "regexp" and "glob" (Policy-15-17)
+ * expect: Permit, Deny, Undetermined
+ */
+TESTSUITE01(10){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s10a", "r10");
+    QA(1, "r10a", "15ba");
+    QA(1, "r10c", "15a1");
+    QC(1, PolicyEffect::PERMIT);
+
+    QU(2, "s10b", "r10");
+    QA(2, "r10a", "15ba");
+    QA(2, "r10c", "15a1");
+    QC(2, PolicyEffect::DENY);
+
+    QU(3, "s10c", "r10");
+    QA(3, "r10a", "15ba");
+    QA(3, "r10c", "15a1");
+    QC(3, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-applicable", target-matching by "uri.authority"
+ * expect: Permit
+ */
+TESTSUITE01(11){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s15", "device:pim.contacts");
+    QA(1, "uri", "//buu.com.pl");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", target-matching by "uri.authority"
+ * expect: Permit
+ */
+TESTSUITE01(12){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s16", "device:pim.contacts");
+    QA(1, "uri", "//v.com.pl");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", target-matching by "version"
+ * expect: Permit, Deny
+ */
+TESTSUITE01(13){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s17a", "resource4");
+    QA(1, "version", "4");
+    QC(1, PolicyEffect::PERMIT);
+
+    QU(2, "s17b", "resource4");
+    QA(2, "version", "4");
+    QC(2, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", subject-matching by "uri"
+ * expect: Permit, Permit, Permit
+ */
+TESTSUITE01(14){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s18a", "device:pim.contacts");
+    QA(1, "uri", "buu.com.pl");
+    QC(1, PolicyEffect::PERMIT);
+
+    QU(2, "s18b", "device:pim.contacts");
+    QA(2, "uri", "buu.com.pl");
+    QC(2, PolicyEffect::PERMIT);
+
+    QU(3, "s18c", "device:pim.contacts");
+    QA(3, "uri", "buu.com.pl");
+    QC(3, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", target-matching by attribute
+ * expect: Deny, Permit
+ */
+TESTSUITE01(15){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s19.1", "resource4");
+    QA(1, "key-root-trust", "voperator");
+    QC(1, PolicyEffect::DENY);
+
+    QU(2, "s19.2", "resource4");
+    QA(2, "key-root-trust", "voperator");
+    QC(2, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", UTF-8 sign
+ * expect: Deny, Permit
+ */
+TESTSUITE01(16){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s20.1", "resource4");
+    QA(1, "signer-id", "v7zha89%49x£$");
+    QC(1, PolicyEffect::DENY);
+
+    QU(2, "s20.2", "resource4");
+    QA(2, "signer-id", "v7zha89%49x£$");
+    QC(2, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", for unknown resource
+ * expect: Not Applicable, Permit
+ */
+TESTSUITE01(17){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s21", "undetermined");
+    QC(1, PolicyDecision::NOT_APPLICABLE);
+
+
+    QU(2, "s21a", "undetermined");
+    QC(2, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", for wrong resource and version
+ * expect: Not Applicable
+ */
+TESTSUITE01(18){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s23", "device:pim.contacts");
+    QA(1, "version", "undetermined");
+    QC(1, PolicyDecision::NOT_APPLICABLE);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "or" for subject and resource.
+ * expect: Permit
+ */
+TESTSUITE01(19){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s24", "device:pim");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "and" condition for resource, subject and environment.
+ * expect: Permit
+ */
+TESTSUITE01(20){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s25.1", "device:pim.contacts");
+    QA(1, "version", "5");
+    QA(1, "roaming", "off");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "and" condition for resource and subject
+ * expect: Not Applicable,
+ */
+TESTSUITE01(21){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s25.2", "device:pim.contacts");
+    QA(1, "version", "undetermined");
+    QC(1, PolicyDecision::NOT_APPLICABLE);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permit-overrides", logical "and" condition with undetermined inputs
+ * expect: Undetermined
+ */
+TESTSUITE01(22){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    QU(1, "s25.3", "device:pim.contacts");
+// undetermined    QA(1, "version", "");
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permit-overrides", logical "or" condition with undetermined inputs
+ * expect: Undetermined
+ */
+TESTSUITE01(23){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    QU(1, "s25.4", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "", true);
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "and" and "or" conditions for resource and subject
+ * expect: Permit
+ */
+TESTSUITE01(24){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    QU(1, "s26.1", "device:pim.contacts");
+    QA(1, "version", "5");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "and" and "or" conditions with undetermined inputs
+ * expect: Permit
+ */
+TESTSUITE01(25){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    QU(1, "s26.2", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "", true);
+    QC(1,  PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "and" and "or" conditions with undetermined inputs
+ * expect: Permit
+ */
+TESTSUITE01(26){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    QU(1, "s26.3", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "", true);
+    QC(1,  PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permit-overrides", logical "and" and "or" conditions with undetermined inputs
+ * expect: Undetermined
+ */
+TESTSUITE01(27){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    QU(1, "s26.4", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permit-overrides", logical "and" and "or" conditions with undetermined inputs
+ * expect: Permit
+ */
+TESTSUITE01(28){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    QU(1, "s27.1", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permit-overrides", logical "and" and "or" conditions with undetermined inputs
+ * expect: Undetermined
+ */
+TESTSUITE01(29){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    QU(1, "s27.2", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "and" and "or" conditions with undetermined inputs
+ * expect: Not Applicable
+ */
+TESTSUITE01(30){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    QU(1, "s27.3", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyDecision::NOT_APPLICABLE);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "and" and "or" conditions with undetermined inputs
+ * expect: Permit
+ */
+TESTSUITE01(31){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    QU(1, "s27.4", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "or" conditions
+ * expect: Permit
+ */
+TESTSUITE01(32){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    QU(1, "s28", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "and" and "or" conditions
+ * expect: Permit
+ */
+TESTSUITE01(33){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    QU(1, "s29", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "and" and "or" conditions
+ * expect: Undetermined
+ */
+TESTSUITE01(34){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    QU(1, "s30.1", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" and "or" conditions
+ * expect: Undetermined
+ */
+TESTSUITE01(35){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    QU(1, "s30.2", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" and "or" conditions
+ * expect: Undetermined
+ */
+TESTSUITE01(36){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    QU(1, "s30.3", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" and "or" conditions
+ * expect: Permit
+ */
+TESTSUITE01(37){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    QU(1, "s30.4", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "deny-overrides", logical "and" and "or" conditions
+ * expect: Undetermined
+ */
+TESTSUITE01(38){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    QU(1, "s31.1", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "deny-overrides", logical "and" and "or" conditions
+ * expect: Deny
+ */
+TESTSUITE01(39){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s31.2.1", "device:pim.contacts");
+    QC(1, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "deny-overrides", logical "and" and "or" conditions
+ * expect: Undetermined
+ */
+TESTSUITE01(40){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s31.2.2", "device:pim.contacts");
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "deny-overrides", logical "and" and "or" conditions
+ * expect: Undetermined
+ */
+TESTSUITE01(41){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s31.3", "device:pim.contacts");
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" and "or" conditions
+ * expect: Undetermined
+ */
+TESTSUITE01(42){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s32.1", "device:pim.contacts");
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" and "or" conditions
+ * expect: Permit
+ */
+TESTSUITE01(43){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s32.2.1", "device:pim.contacts");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" and "or" conditions
+ * expect: Undetermined
+ */
+TESTSUITE01(44){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s32.2.2", "device:pim.contacts");
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" and "or" conditions
+ * expect: Undetermined
+ */
+TESTSUITE01(45){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s32.3", "device:pim.contacts");
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" and "or" conditions
+ * expect: Undetermined
+ */
+TESTSUITE01(46){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s33.1", "device:pim.contacts");
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" condition
+ * expect: Permit
+ */
+TESTSUITE01(47){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s33.2", "device:pim.contacts");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" and "or" conditions
+ * expect: Permit
+ */
+TESTSUITE01(48){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s33.3", "device:pim.contacts");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" condition
+ * expect: Undetermined
+ */
+TESTSUITE01(49){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //Test undetermined, we have to refine this tests to test something
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s34.1", "device:pim.contacts");
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" condition
+ * expect: Undetermined
+ */
+TESTSUITE01(50){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s34.2", "device:pim.contacts");
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" condition
+ * expect: Undetermined
+ */
+TESTSUITE01(51){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s35.1", "device:pim.contacts");
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", logical "and" condition
+ * expect: Undetermined
+ */
+TESTSUITE01(52){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QU(1, "s35.2", "device:pim.contacts");
+    QC(1, PolicyResult::UNDETERMINED);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "and" condition
+ * expect: Not Applicable
+ */
+TESTSUITE01(53){
+    CLEANENV(GENERAL_TEST_POLICY_UNDETERMIND);
+    QU(1, "s36", "device:pim.contacts");
+    //undetermined
+    //QA(1, "version", "undetermined", true);
+    QC(1, PolicyDecision::NOT_APPLICABLE);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", logical "and" condition
+ * expect: Prompt Oneshot
+ */
+TESTSUITE01(54){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s37", "device:pim.contacts.read");
+    QC(1, PolicyEffect::PROMPT_ONESHOT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Prompt Session, Prompt Session
+ */
+TESTSUITE01(55){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s38", "device:pim.contacts.read");
+    QC(1, PolicyEffect::PROMPT_SESSION);
+
+    QU(2, "s38.4", "device:pim.contacts.read");
+    QC(2, PolicyEffect::PROMPT_SESSION);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Prompt Blanket, Prompt Blanket
+ */
+TESTSUITE01(56){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s39", "device:pim.contacts.read");
+    QC(1, PolicyEffect::PROMPT_BLANKET);
+
+    QU(2, "s39.4", "device:pim.contacts.read");
+    QC(2, PolicyEffect::PROMPT_BLANKET);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(57){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s40", "r40");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(58){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s41", "r41");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Deny
+ */
+TESTSUITE01(59){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s42.1", "r42.1");
+    QC(1, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Deny
+ */
+TESTSUITE01(60){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s42.2", "r42.2");
+    QC(1, PolicyEffect::DENY);
+
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "deny-overrides", and logical conditions
+ * expect: Deny
+ */
+TESTSUITE01(61){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s43.1", "r43.1");
+    QC(1, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "deny-overrides", and logical conditions
+ * expect: Deny
+ */
+TESTSUITE01(62){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s43.2", "r43.2");
+    QC(1,  PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(63){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s44.1", "r44.1");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "permitt-overrides", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(64){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s44.2", "r44.2");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(65){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s45.1", "r45.1");
+    QC(1,  PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Deny
+ */
+TESTSUITE01(66){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s45.2", "r45.2");
+    QC(1, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(67){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s46.1", "r46.1");
+    QC(1,  PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(68){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s46.2", "r46.2");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Deny
+ */
+TESTSUITE01(69){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s47.1", "r47.1");
+    QC(1, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Deny
+ */
+TESTSUITE01(70){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s47.2", "r47.2");
+    QC(1,  PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(71){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "s48", "device:pim.contacts");
+    QA(1, "uri", "http://www.test.pl:80");
+    QC(1,  PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Deny
+ */
+TESTSUITE01(72){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "BF00", "BFR00");
+    QC(1, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(73){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "BF01", "BFR01");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(74){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "BF02", "BFR02");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Deny
+ */
+TESTSUITE01(75){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "BF03", "BFR03");
+    QC(1,  PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(76){
+    CLEANENV(GENERAL_TEST_POLICY);
+    QU(1, "BF04", "BFR04");
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target" and "first-applicable", and logical conditions
+ * expect: Deny
+ */
+TESTSUITE01(77){
+    CLEANENV(GENERAL_TEST_POLICY);
+    FunctionParamImpl functionParam;
+    functionParam.addAttribute("param:recipients","+44091234");
+    QU(1, "paramTestSubject", "resource");
+    QA(1, "dev-cap","messaging");
+    QCP(1, &functionParam, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target" and "first-applicable", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(78){
+    CLEANENV(GENERAL_TEST_POLICY);
+    FunctionParamImpl functionParam;
+    functionParam.addAttribute("param:recipients","+44081234");
+    QU(1, "paramTestSubject", "resource");
+    QA(1, "dev-cap","messaging");
+    QCP(1, &functionParam, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target" and "first-applicable", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(79){
+    CLEANENV(GENERAL_TEST_POLICY);
+    FunctionParamImpl functionParam;
+    functionParam.addAttribute("param:recipients","+4812345656");
+    QU(1, "paramTestSubject", "resource");
+    QA(1, "dev-cap","messaging");
+    QCP(1, &functionParam, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target" and "first-applicable", and logical conditions
+ * expect: Not Applicable
+ */
+TESTSUITE01(80){
+    CLEANENV(GENERAL_TEST_POLICY);
+    FunctionParamImpl functionParam;
+    functionParam.addAttribute("param:quality","low");
+    QU(1, "paramTestSubject", "resource");
+    QA(1, "dev-cap","messaging");
+    QCP(1, &functionParam, PolicyDecision::NOT_APPLICABLE);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target" and "first-applicable", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(81){
+    CLEANENV(GENERAL_TEST_POLICY);
+    FunctionParamImpl functionParam;
+    functionParam.addAttribute("param:quality", "high");
+    QU(1, "paramTestSubject", "resource");
+    QA(1, "dev-cap","camera");
+    QCP(1, &functionParam, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target" and "first-applicable", and logical conditions
+ * expect: Permit
+ */
+TESTSUITE01(82){
+    CLEANENV(GENERAL_TEST_POLICY);
+
+    QU(1, "s61a", "r61a");
+    QC(1, PolicyEffect::DENY);
+
+    FunctionParamImpl functionParam;
+    functionParam.addAttribute("param:name", "type");
+    QU(2, "s61b", "r61b");
+    QCP(2, &functionParam, PolicyEffect::PERMIT);
+
+    QU(3, "s61c", "r61c");
+    QC(3,  PolicyEffect::DENY);
+
+    FunctionParamImpl functionParam4;
+    functionParam4.addAttribute("param:name", "type");
+    functionParam4.addAttribute("param:name", "port");
+    QU(4, "s61d", "r61d");
+    QCP(4, &functionParam4, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Deny, Deny, Permit
+ */
+TESTSUITE01(83){
+    CLEANENV(GENERAL_TEST_POLICY_TEST);
+
+    PermissionList sList;
+    sList.push_back(PermissionTriple(1, "b1", Preference::PREFERENCE_PERMIT));
+    sList.push_back(PermissionTriple(2, "bb2", Preference::PREFERENCE_DENY));
+    sList.push_back(PermissionTriple(3, "d3", Preference::PREFERENCE_DEFAULT));
+    SettingsLogic::setWidgetDevCapSettings(sList);
+
+    QU(1, "a1", "b1");
+    QC(1,  PolicyEffect::DENY);
+
+    QU(2, "aa2", "bb2");
+    QC(2, PolicyEffect::DENY);
+
+    QU(3, "c3", "d3");
+    QC(3, PolicyEffect::PERMIT);
+}
+
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Prompt Oneshot
+ */
+TESTSUITE01(84){
+    CLEANENV(GENERAL_TEST_POLICY_TEST);
+    PermissionList sList;
+    sList.push_back(PermissionTriple(3, "d3", Preference::PREFERENCE_ONE_SHOT_PROMPT));
+    SettingsLogic::setWidgetDevCapSettings(sList);
+    QU(3, "c3", "d3");
+    QC(3, PolicyEffect::PROMPT_ONESHOT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Not Applicable, Deny, Permit
+ */
+TESTSUITE01(85){
+    CLEANENV(GENERAL_TEST_POLICY_TEST);
+
+    PermissionList sList;
+    sList.push_back(PermissionTriple(1, "bnp", Preference::PREFERENCE_DEFAULT));
+    sList.push_back(PermissionTriple(2, "bbnp", Preference::PREFERENCE_DENY));
+    sList.push_back(PermissionTriple(3, "dnp", Preference::PREFERENCE_PERMIT));
+
+    SettingsLogic::setWidgetDevCapSettings(sList);
+
+    QU(1, "anp", "bnp");
+    QC(1, PolicyDecision::NOT_APPLICABLE);
+
+    QU(2, "aanp", "bbnp");
+    QC(2, PolicyEffect::DENY);
+
+    QU(3, "cnp", "dnp");
+    QC(3, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Deny, Deny, Permit, Deny
+ */
+TESTSUITE01(86){
+    CLEANENV(GENERAL_TEST_POLICY_TEST);
+
+    PermissionList sList;
+    sList.push_back(PermissionTriple(1, "b1", Preference::PREFERENCE_DEFAULT));
+    sList.push_back(PermissionTriple(2, "bb", Preference::PREFERENCE_DENY));
+    sList.push_back(PermissionTriple(3, "d3", Preference::PREFERENCE_PERMIT));
+    sList.push_back(PermissionTriple(4, "b1", Preference::PREFERENCE_PERMIT));
+    sList.push_back(PermissionTriple(5, "bb2", Preference::PREFERENCE_DENY));
+    sList.push_back(PermissionTriple(6, "d3", Preference::PREFERENCE_DEFAULT));
+
+    SettingsLogic::setWidgetDevCapSettings(sList);
+
+    QU(1, "a1", "b1");
+    QC(1, PolicyEffect::DENY);
+
+    QU(2, "aa", "bb");
+    QC(2, PolicyEffect::DENY);
+
+    QU(3, "c3", "d3");
+    QC(3, PolicyEffect::PERMIT);
+
+    QU(5, "aa2", "bb2");
+    QC(5, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Permit, Permit, Deny, Permit, Permit
+ */
+TESTSUITE01(87){
+    CLEANENV(GENERAL_TEST_POLICY_TEST);
+
+    QU(1, "c3", "d3");
+    QC(1, PolicyEffect::PERMIT);
+
+    QU(2, "aa2", "bb2");
+    QC(2, PolicyEffect::PERMIT);
+
+    SettingsLogic::updateDevCapSetting("d3", Preference::PREFERENCE_DENY);
+    SettingsLogic::updateDevCapSetting("bb2", Preference::PREFERENCE_DEFAULT);
+
+    QC(1, PolicyEffect::DENY);
+
+    QC(2, PolicyEffect::PERMIT);
+
+    SettingsLogic::updateDevCapSetting("d3", Preference::PREFERENCE_PERMIT);
+
+    QC(1, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested algorithm "first-matching-target", and logical conditions
+ * expect: Permit, Permit, Deny, Permit, Permit, Deny, Deny, Deny, Permit, Deny
+ */
+TESTSUITE01(88){
+    CLEANENV(GENERAL_TEST_POLICY_GSETTINGS);
+    std::string d3("d3");
+
+    QU(1, "c3", "d3");
+    QC(1, PolicyEffect::PERMIT);
+
+    QU(2, "aa2", "bb2");
+    QC(2, PolicyEffect::PERMIT);
+
+    QU(3, "a1", "d3");
+    QC(3, PolicyEffect::DENY);
+
+    SettingsLogic::updateDevCapSetting(d3, Preference::PREFERENCE_DEFAULT);
+
+    QC(1, PolicyEffect::PERMIT);
+
+    QC(2, PolicyEffect::PERMIT);
+
+    QC(3, PolicyEffect::DENY);
+
+    SettingsLogic::updateDevCapSetting(d3, Preference::PREFERENCE_DENY);
+
+    QC(1, PolicyEffect::DENY);
+
+    QC(3, PolicyEffect::DENY);
+
+    SettingsLogic::updateDevCapSetting(d3, Preference::PREFERENCE_PERMIT);
+
+    QC(1, PolicyEffect::PERMIT);
+
+    QC(3, PolicyEffect::DENY);
+}
+
+/**
+ * Following tests assume that default WAC2.0Policy.xml and TizenPolicy.xml
+ * are chagned to test policies.
+ */
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested parsing WAC2.0 Policy file.
+ * expect: Permit, Deny
+ */
+TESTSUITE01(89){
+    CLEANENV_KNOWN_POLICY_LOCATIONS;
+    WidgetHandle wacHandle =
+            InstallerMockup::registerWidget(AceDB::AppTypes::WAC20);
+
+    QU(wacHandle, "wac", "wac1resource");
+    QC(wacHandle, PolicyEffect::PERMIT);
+
+    QU(wacHandle, "wac", "wac2resource");
+    QC(wacHandle, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested parsing Tizen Policy file.
+ * expect: Permit, Deny
+ */
+TESTSUITE01(90){
+    CLEANENV_KNOWN_POLICY_LOCATIONS;
+
+    WidgetHandle tizenHandle =
+            InstallerMockup::registerWidget(AceDB::AppTypes::Tizen);
+
+    QU(tizenHandle, "tizen", "tizen1resource");
+    QTC(tizenHandle, PolicyEffect::PERMIT);
+
+    QU(tizenHandle, "tizen", "tizen2resource");
+    QTC(tizenHandle, PolicyEffect::DENY);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested parsing WAC2.0 Policy file.
+ * expect: Not Applicable, Not Applicable
+ */
+TESTSUITE01(91){
+    CLEANENV_KNOWN_POLICY_LOCATIONS;
+    WidgetHandle wacHandle =
+            InstallerMockup::registerWidget(AceDB::AppTypes::WAC20);
+
+    QU(wacHandle, "wac", "tizen1resource");
+    QC(wacHandle, PolicyDecision::NOT_APPLICABLE);
+
+    QU(wacHandle, "wac", "tizen2resource");
+    QC(wacHandle, PolicyDecision::NOT_APPLICABLE);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested parsing Tizen Policy file.
+ * expect: Not Applicable, Not Applicable
+ */
+TESTSUITE01(92){
+    CLEANENV_KNOWN_POLICY_LOCATIONS;
+
+    WidgetHandle tizenHandle =
+            InstallerMockup::registerWidget(AceDB::AppTypes::Tizen);
+
+    QU(tizenHandle, "tizen", "wac1resource");
+    QTC(tizenHandle, PolicyDecision::NOT_APPLICABLE);
+
+    QU(tizenHandle, "tizen", "wac2resource");
+    QTC(tizenHandle, PolicyDecision::NOT_APPLICABLE);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested parsing WAC2.0 Policy file.
+ * expect: Permit, Permit
+ */
+TESTSUITE01(93){
+    CLEANENV_KNOWN_POLICY_LOCATIONS;
+    WidgetHandle wacHandle =
+            InstallerMockup::registerWidget(AceDB::AppTypes::WAC20);
+
+    QU(wacHandle, "wac2", "wac1resource");
+    QC(wacHandle, PolicyEffect::PERMIT);
+
+    QU(wacHandle, "wac2", "wac2resource");
+    QC(wacHandle, PolicyEffect::PERMIT);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Tested parsing Tizen Policy file.
+ * expect: Deny, Deny
+ */
+TESTSUITE01(94){
+    CLEANENV_KNOWN_POLICY_LOCATIONS;
+
+    WidgetHandle tizenHandle =
+            InstallerMockup::registerWidget(AceDB::AppTypes::Tizen);
+
+    QU(tizenHandle, "tizen2", "tizen1resource");
+    QTC(tizenHandle, PolicyEffect::DENY);
+
+    QU(tizenHandle, "tizen2", "tizen2resource");
+    QTC(tizenHandle, PolicyEffect::DENY);
+}
diff --git a/tests/ace/TestSuite02.cpp b/tests/ace/TestSuite02.cpp
new file mode 100644 (file)
index 0000000..c27f418
--- /dev/null
@@ -0,0 +1,980 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    TestSuite02.cpp
+ * @author  unknown
+ * @version 1.0
+ * @brief   Test cases for Attribute class.
+ */
+#include <string>
+
+#include <dpl/log/log.h>
+#include <dpl/test/test_runner.h>
+
+#include <ace/Attribute.h>
+#include <ace-dao-ro/BaseAttribute.h>
+#include <ace/PolicyEvaluator.h>
+
+#include "PEPSingleton.h"
+
+#define POLICY_ATTR_EXAMPLE  "/usr/etc/ace/attr_policy-example.xml"
+#define POLICY_ATTR_EXAMPLE1 "/usr/etc/ace/attr_policy-example1.xml"
+#define POLICY_ATTR_EXAMPLE2 "/usr/etc/ace/attr_policy-example2.xml"
+#define POLICY_ATTR_EXAMPLE3 "/usr/etc/ace/attr_policy-example3.xml"
+#define POLICY_ATTR_EXAMPLE4 "/usr/etc/ace/attr_policy-example4.xml"
+#define POLICY_ATTR_EXAMPLE5 "/usr/etc/ace/attr_policy-example5.xml"
+#define POLICY_ATTR_EXAMPLE6 "/usr/etc/ace/attr_policy-example6.xml"
+#define POLICY_ATTR_EXAMPLE7 "/usr/etc/ace/attr_policy-example7.xml"
+#define POLICY_ATTR_EXAMPLE8 "/usr/etc/ace/attr_policy-example8.xml"
+
+#define CLEANENV(d)                                                         \
+    do{                                                                     \
+        if (PEPSingleton::Instance().getPdp()->getCurrentPolicy() != (d)) { \
+            PEPSingleton::Instance().getPdp()->updatePolicy(d);             \
+        }                                                                   \
+    }while(0)
+
+#define PEPTR PEPSingleton::Instance().getPdp()
+
+#define TESTSUITE02(n) \
+RUNNER_TEST(ts02_extract_attributes_tests_ ## n)
+
+using namespace AceDB;
+
+bool AttrEqual(const AttributeSet &actual, AttributeSet * expected)
+{
+    bool match = false;
+    for (AttributeSet::const_iterator ita = actual.begin();
+         ita != actual.end();
+         ++ita)
+    {
+        match = false;
+        for (AttributeSet::const_iterator ite = expected->begin();
+             ite != expected->end();
+             ++ite)
+        {
+            if ((*(*ita)->getName() == *(*ite)->getName()) &&
+                ((*ita)->getType() == (*ite)->getType()))
+            {
+                match = true;
+            }
+        }
+        if (!match)
+        {
+            LogError("Not found " <<
+                 *(*ita)->getName() <<
+                 " " << static_cast<int>((*ita)->getType()));
+            return false;
+        }
+    }
+    return true;
+}
+
+RUNNER_TEST_GROUP_INIT(ACE_TEST_SUITE_02)
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Test get value of attributes from database.
+ * expect: Values should be equal.
+ */
+TESTSUITE02(01){
+    CLEANENV(POLICY_ATTR_EXAMPLE);
+
+    AttributeSet attrSet;
+    std::string n1("name");
+    BaseAttributePtr a1(new Attribute(&n1,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a1);
+
+
+    std::string n2("resource-id");
+    BaseAttributePtr a2(new Attribute(&n2,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a2);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Test get value of attributes from database.
+ * expect: Values should be equal.
+ */
+TESTSUITE02(02){
+    CLEANENV(POLICY_ATTR_EXAMPLE1);
+
+    AttributeSet attrSet;
+
+    std::string n3("uri.host");
+    BaseAttributePtr a3(new Attribute(&n3,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a3);
+
+    std::string n4("key-root-trust");
+    BaseAttributePtr a4(new Attribute(&n4,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a4);
+
+    std::string n5("id");
+    BaseAttributePtr a5(new Attribute(&n5,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a5);
+
+    std::string n6("signer-id");
+    BaseAttributePtr a6(new Attribute(&n6,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a6);
+
+    std::string n7("version");
+    BaseAttributePtr a7(new Attribute(&n7,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a7);
+
+    std::string n8("r8v2");
+    BaseAttributePtr a8(new Attribute(&n8,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a8);
+
+    std::string n9("author");
+    BaseAttributePtr a9(new Attribute(&n9,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a9);
+
+    std::string n10("r9a.scheme");
+    BaseAttributePtr a10(new Attribute(&n10,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a10);
+
+    std::string n11("r9b.authority");
+    BaseAttributePtr a11(new Attribute(&n11,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a11);
+
+    std::string n12("r9c.scheme-authority");
+    BaseAttributePtr a12(new Attribute(&n12,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a12);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Test get value of attributes from database.
+ * expect: Values should be equal.
+ */
+TESTSUITE02(03){
+    CLEANENV(POLICY_ATTR_EXAMPLE2);
+
+    AttributeSet attrSet;
+
+    std::string n1("id");
+    BaseAttributePtr a1(new Attribute(&n1,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a1);
+
+    std::string n3("version");
+    BaseAttributePtr a3(new Attribute(&n3,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a3);
+
+    std::string n2("resource-id");
+    BaseAttributePtr a2(new Attribute(&n2,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a2);
+
+    std::string n4("author");
+    BaseAttributePtr a4(new Attribute(&n4,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a4);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Test get value of attributes from database.
+ * expect: Values should be equal.
+ */
+TESTSUITE02(04){
+    CLEANENV(POLICY_ATTR_EXAMPLE3);
+
+    AttributeSet attrSet;
+
+    std::string n1("id");
+    BaseAttributePtr a1(new Attribute(&n1,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a1);
+
+    std::string n3("version");
+    BaseAttributePtr a3(new Attribute(&n3,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a3);
+
+    std::string n2("resource-id");
+    BaseAttributePtr a2(new Attribute(&n2,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a2);
+
+    std::string n4("author");
+    BaseAttributePtr a4(new Attribute(&n4,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a4);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
+TESTSUITE02(05){
+    CLEANENV(POLICY_ATTR_EXAMPLE4);
+
+    AttributeSet attrSet;
+
+    std::string n1("id");
+    BaseAttributePtr a1(new Attribute(&n1,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a1);
+
+    std::string n3("version");
+    BaseAttributePtr a3(new Attribute(&n3,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a3);
+
+
+    std::string n2("resource-id");
+    BaseAttributePtr a2(new Attribute(&n2,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a2);
+
+    std::string n4("author");
+    BaseAttributePtr a4(new Attribute(&n4,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a4);
+
+    std::string n5("author");
+    BaseAttributePtr a5(new Attribute(&n5,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Environment));
+    attrSet.insert(a5);
+
+    std::string n6("version");
+    BaseAttributePtr a6(new Attribute(&n6,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Environment));
+    attrSet.insert(a6);
+
+    std::string n7("ver");
+    BaseAttributePtr a7(new Attribute(&n7,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Environment));
+    attrSet.insert(a7);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Test get value of attributes from database.
+ * expect: Values should be equal.
+ */
+TESTSUITE02(06){
+    CLEANENV(POLICY_ATTR_EXAMPLE5);
+
+    AttributeSet attrSet;
+
+    std::string n3("uri.host");
+    BaseAttributePtr a3(new Attribute(&n3,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a3);
+
+    std::string n4("key-root-trust");
+    BaseAttributePtr a4(new Attribute(&n4,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a4);
+
+    std::string n5("id");
+    BaseAttributePtr a5(new Attribute(&n5,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a5);
+
+    std::string n6("signer-id");
+    BaseAttributePtr a6(new Attribute(&n6,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a6);
+
+    std::string n7("version");
+    BaseAttributePtr a7(new Attribute(&n7,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a7);
+
+    std::string n13("name");
+    BaseAttributePtr a13(new Attribute(&n13,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a13);
+
+    std::string n14("resource-id");
+    BaseAttributePtr a14(new Attribute(&n14,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a14);
+
+    std::string n15("r8v2");
+    BaseAttributePtr a15(new Attribute(&n15,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a15);
+
+    std::string n16("author");
+    BaseAttributePtr a16(new Attribute(&n16,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a16);
+
+    std::string n17("r9a.scheme");
+    BaseAttributePtr a17(new Attribute(&n17,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a17);
+
+    std::string n18("r9b.authority");
+    BaseAttributePtr a18(new Attribute(&n18,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a18);
+
+    std::string n19("r9c.scheme-authority");
+    BaseAttributePtr a19(new Attribute(&n19,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a19);
+
+    std::string n20("resource-id");
+    BaseAttributePtr a20(new Attribute(&n20,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a20);
+
+    std::string n8("r8v2");
+    BaseAttributePtr a8(new Attribute(&n8,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a8);
+
+    std::string n9("author");
+    BaseAttributePtr a9(new Attribute(&n9,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a9);
+
+    std::string n10("r9a.scheme");
+    BaseAttributePtr a10(new Attribute(&n10,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a10);
+
+    std::string n11("r9b.authority");
+    BaseAttributePtr a11(new Attribute(&n11,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a11);
+
+    std::string n12("r9c.scheme-authority");
+    BaseAttributePtr a12(new Attribute(&n12,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a12);
+
+    std::string n21("resource-id");
+    BaseAttributePtr a21(new Attribute(&n21,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a21);
+
+    std::string n22("r8v2");
+    BaseAttributePtr a22(new Attribute(&n22,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a22);
+
+    std::string n23("author");
+    BaseAttributePtr a23(new Attribute(&n23,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a23);
+
+    std::string n24("r9a.scheme");
+    BaseAttributePtr a24(new Attribute(&n24,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a24);
+
+    std::string n25("r9b.authority");
+    BaseAttributePtr a25(new Attribute(&n25,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a25);
+
+    std::string n26("r9c.scheme-authority");
+    BaseAttributePtr a26(new Attribute(&n26,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a26);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Test get value of attributes from database.
+ * expect: Values should be equal.
+ */
+TESTSUITE02(07){
+    CLEANENV(POLICY_ATTR_EXAMPLE6);
+
+    AttributeSet attrSet;
+
+    std::string n3("s-uri.host");
+    BaseAttributePtr a3(new Attribute(&n3,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a3);
+
+    std::string n4("s-key-root-trust");
+    BaseAttributePtr a4(new Attribute(&n4,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a4);
+
+    std::string n5("s-id");
+    BaseAttributePtr a5(new Attribute(&n5,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a5);
+
+    std::string n6("s-signer-id");
+    BaseAttributePtr a6(new Attribute(&n6,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a6);
+
+    std::string n7("s-version");
+    BaseAttributePtr a7(new Attribute(&n7,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a7);
+
+    std::string n13("s-name");
+    BaseAttributePtr a13(new Attribute(&n13,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a13);
+
+    std::string n14("s-resource-id");
+    BaseAttributePtr a14(new Attribute(&n14,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a14);
+
+    std::string n15("s-r8v2");
+    BaseAttributePtr a15(new Attribute(&n15,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a15);
+
+    std::string n16("s-author");
+    BaseAttributePtr a16(new Attribute(&n16,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a16);
+
+    std::string n17("s-r9a.scheme");
+    BaseAttributePtr a17(new Attribute(&n17,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a17);
+
+    std::string n18("s-r9b.authority");
+    BaseAttributePtr a18(new Attribute(&n18,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a18);
+
+    std::string n19("s-r9c.scheme-authority");
+    BaseAttributePtr a19(new Attribute(&n19,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a19);
+
+    std::string n20("r-resource-id");
+    BaseAttributePtr a20(new Attribute(&n20,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a20);
+
+    std::string n8("r-r8v2");
+    BaseAttributePtr a8(new Attribute(&n8,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a8);
+
+    std::string n9("r-author");
+    BaseAttributePtr a9(new Attribute(&n9,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a9);
+
+    std::string n10("r-r9a.scheme");
+    BaseAttributePtr a10(new Attribute(&n10,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a10);
+
+    std::string n11("r-r9b.authority");
+    BaseAttributePtr a11(new Attribute(&n11,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a11);
+
+    std::string n12("r-r9c.scheme-authority");
+    BaseAttributePtr a12(new Attribute(&n12,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a12);
+
+    std::string n21("e-resource-id");
+    BaseAttributePtr a21(new Attribute(&n21,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a21);
+
+    std::string n22("e-r8v2");
+    BaseAttributePtr a22(new Attribute(&n22,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a22);
+
+    std::string n23("e-author");
+    BaseAttributePtr a23(new Attribute(&n23,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a23);
+
+    std::string n24("e-r9a.scheme");
+    BaseAttributePtr a24(new Attribute(&n24,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a24);
+
+    std::string n25("e-r9b.authority");
+    BaseAttributePtr a25(new Attribute(&n25,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a25);
+
+    std::string n26("e-r9c.scheme-authority");
+    BaseAttributePtr a26(new Attribute(&n26,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a26);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Test get value of attributes from database.
+ * expect: Values should be equal.
+ */
+TESTSUITE02(08){
+    CLEANENV(POLICY_ATTR_EXAMPLE2);
+
+    AttributeSet attrSet;
+
+    std::string n1("id");
+    BaseAttributePtr a1(new Attribute(&n1,
+                                      Attribute::Match::Glob,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a1);
+
+    std::string n3("version");
+    BaseAttributePtr a3(new Attribute(&n3,
+                                      Attribute::Match::Glob,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a3);
+
+
+    std::string n2("resource-id");
+    BaseAttributePtr a2(new Attribute(&n2,
+                                      Attribute::Match::Glob,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a2);
+
+    std::string n4("author");
+    BaseAttributePtr a4(new Attribute(&n4,
+                                      Attribute::Match::Glob,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a4);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Test get value of attributes from database.
+ * expect: Values should be equal.
+ */
+TESTSUITE02(09){
+    CLEANENV(POLICY_ATTR_EXAMPLE2);
+
+    AttributeSet attrSet;
+
+    std::string n1("id");
+    BaseAttributePtr a1(new Attribute(&n1,
+                                      Attribute::Match::Regexp,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a1);
+
+    std::string n3("version");
+    BaseAttributePtr a3(new Attribute(&n3,
+                                      Attribute::Match::Regexp,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a3);
+
+
+    std::string n2("resource-id");
+    BaseAttributePtr a2(new Attribute(&n2,
+                                      Attribute::Match::Regexp,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a2);
+
+    std::string n4("author");
+    BaseAttributePtr a4(new Attribute(&n4,
+                                      Attribute::Match::Regexp,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a4);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Test get value of attributes from database.
+ * expect: Values should be equal.
+ */
+TESTSUITE02(10){
+    CLEANENV(POLICY_ATTR_EXAMPLE2);
+
+    AttributeSet attrSet;
+
+    std::string n1("id");
+    BaseAttributePtr a1(new Attribute(&n1,
+                                      Attribute::Match::Regexp,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a1);
+
+    std::string n3("version");
+    BaseAttributePtr a3(new Attribute(&n3,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a3);
+
+
+    std::string n2("resource-id");
+    BaseAttributePtr a2(new Attribute(&n2,
+                                      Attribute::Match::Glob,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a2);
+
+    std::string n4("author");
+    BaseAttributePtr a4(new Attribute(&n4,
+                                      Attribute::Match::Regexp,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a4);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Test get value of attributes from database.
+ * expect: Values should be equal.
+ */
+TESTSUITE02(11){
+    CLEANENV(POLICY_ATTR_EXAMPLE7);
+
+    AttributeSet attrSet;
+
+    std::string n3("uri.host");
+    BaseAttributePtr a3(new Attribute(&n3,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a3);
+
+    std::string n4("key-root-trust");
+    BaseAttributePtr a4(new Attribute(&n4,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a4);
+
+    std::string n5("id");
+    BaseAttributePtr a5(new Attribute(&n5,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a5);
+
+    std::string n6("signer-id");
+    BaseAttributePtr a6(new Attribute(&n6,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a6);
+
+    std::string n7("version");
+    BaseAttributePtr a7(new Attribute(&n7,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a7);
+
+    std::string n13("name");
+    BaseAttributePtr a13(new Attribute(&n13,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a13);
+
+    std::string n14("resource-id");
+    BaseAttributePtr a14(new Attribute(&n14,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a14);
+
+    std::string n15("r8v2");
+    BaseAttributePtr a15(new Attribute(&n15,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a15);
+
+    std::string n16("author");
+    BaseAttributePtr a16(new Attribute(&n16,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a16);
+
+    std::string n17("r9a.scheme");
+    BaseAttributePtr a17(new Attribute(&n17,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a17);
+
+    std::string n18("r9b.authority");
+    BaseAttributePtr a18(new Attribute(&n18,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a18);
+
+    std::string n19("r9c.scheme-authority");
+    BaseAttributePtr a19(new Attribute(&n19,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    attrSet.insert(a19);
+
+    std::string n20("resource-id");
+    BaseAttributePtr a20(new Attribute(&n20,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a20);
+
+    std::string n8("r8v2");
+    BaseAttributePtr a8(new Attribute(&n8,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a8);
+
+    std::string n9("author");
+    BaseAttributePtr a9(new Attribute(&n9,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a9);
+
+    std::string n10("r9a.scheme");
+    BaseAttributePtr a10(new Attribute(&n10,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a10);
+
+    std::string n11("r9b.authority");
+    BaseAttributePtr a11(new Attribute(&n11,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a11);
+
+    std::string n12("r9c.scheme-authority");
+    BaseAttributePtr a12(new Attribute(&n12,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Resource));
+    attrSet.insert(a12);
+
+    std::string n21("resource-id");
+    BaseAttributePtr a21(new Attribute(&n21,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a21);
+
+    std::string n22("r8v2");
+    BaseAttributePtr a22(new Attribute(&n22,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a22);
+
+    std::string n23("author");
+    BaseAttributePtr a23(new Attribute(&n23,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a23);
+
+    std::string n24("r9a.scheme");
+    BaseAttributePtr a24(new Attribute(&n24,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a24);
+
+    std::string n25("r9b.authority");
+    BaseAttributePtr a25(new Attribute(&n25,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a25);
+
+    std::string n26("r9c.scheme-authority");
+    BaseAttributePtr a26(new Attribute(&n26,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Environment));
+    attrSet.insert(a26);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Test get value of attributes from database.
+ * expect: Values should be equal.
+ */
+TESTSUITE02(12){
+    CLEANENV(POLICY_ATTR_EXAMPLE8);
+
+    AttributeSet attrSet;
+
+    std::string n1("id");
+    BaseAttributePtr a1(new Attribute(&n1,
+                                      Attribute::Match::Regexp,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a1);
+
+    std::string n3("version");
+    BaseAttributePtr a3(new Attribute(&n3,
+                                      Attribute::Match::Equal,
+                                      Attribute::Type::Subject));
+    attrSet.insert(a3);
+
+
+    std::string n2("resource-id");
+    BaseAttributePtr a2(new Attribute(&n2,
+                                      Attribute::Match::Glob,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a2);
+
+    std::string n4("author");
+    BaseAttributePtr a4(new Attribute(&n4,
+                                      Attribute::Match::Regexp,
+                                      Attribute::Type::Resource));
+    attrSet.insert(a4);
+
+    PEPTR->extractAttributesTest();
+
+    bool result = AttrEqual(attrSet, PEPTR->getAttributeSet());
+    RUNNER_ASSERT(result);
+}
+
diff --git a/tests/ace/TestSuite03.cpp b/tests/ace/TestSuite03.cpp
new file mode 100644 (file)
index 0000000..2832ac8
--- /dev/null
@@ -0,0 +1,654 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    TestSuite03.cpp
+ * @author  Piotr Fatyga (p.fatyga@samsung.com)
+ * @version 0.1
+ * @brief   Test cases for Condition class.
+ */
+
+#include <string>
+
+#include <dpl/log/log.h>
+#include <dpl/test/test_runner.h>
+
+#include <ace/Attribute.h>
+#include <ace-dao-ro/BaseAttribute.h>
+#include <ace/Condition.h>
+
+#define TESTSUITE03(n) \
+RUNNER_TEST(ts03_condtitions_tests_ ## n)
+
+using namespace AceDB;
+
+BaseAttributePtr createAttribute(
+        const char *name,
+        const char * value,
+        const Attribute::Type type = Attribute::Type::Subject)
+{
+    std::string aName(name);
+    BaseAttributePtr attr(new Attribute(&aName, Attribute::Match::Equal, type));
+    if(value != NULL){
+        std::string aValue(value);
+        DPL::StaticPointerCast<Attribute>(attr)->addValue(&aValue);
+    }
+    return attr;
+}
+
+BaseAttributePtr createAttribute(
+        const char *name,
+        const char *value,
+        const char *value2,
+        const Attribute::Type type = Attribute::Type::Subject)
+{
+    std::string aName(name);
+    BaseAttributePtr attr(new Attribute(&aName, Attribute::Match::Equal, type));
+    if(value != NULL && value2 != NULL ){
+        std::string aValue(value), aValue2(value2);
+        DPL::StaticPointerCast<Attribute>(attr)->addValue(&aValue);
+        DPL::StaticPointerCast<Attribute>(attr)->addValue(&aValue2);
+    }
+    return attr;
+}
+
+
+bool MatchResultEqual(
+        Attribute::MatchResult actual,
+        Attribute::MatchResult  expected)
+{
+    return actual == expected;
+}
+
+bool evaluateResult(
+        Condition con,
+        AttributeSet & attrs,
+        Attribute::MatchResult expectedResult)
+{
+    Attribute::MatchResult matchResult = con.evaluateCondition(&attrs);
+    return MatchResultEqual(matchResult ,expectedResult);
+}
+
+RUNNER_TEST_GROUP_INIT(ACE_TEST_SUITE_03)
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(01){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("r8v2","var2");
+    BaseAttributePtr a3 = createAttribute("author","va3");
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+
+    attrSet.insert(a1);
+    attrSet.insert(a2);
+    attrSet.insert(a3);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRTrue));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(02){
+    Condition con(Condition::AND);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("r8v2","var2");
+    BaseAttributePtr a3 = createAttribute("author","va3");
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+
+    attrSet.insert(a1);
+    attrSet.insert(a2);
+    attrSet.insert(a3);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRTrue));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(03){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("r8v2","var2");
+    BaseAttributePtr a3 = createAttribute("author","va3");
+    BaseAttributePtr a4 = createAttribute("version","wrongValue");
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+
+    attrSet.insert(a2);
+    attrSet.insert(a3);
+    attrSet.insert(a4);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRTrue));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(04){
+    Condition con(Condition::AND);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("r8v2","var2");
+    BaseAttributePtr a3 = createAttribute("author","va3");
+    BaseAttributePtr a4 = createAttribute("version","bad");
+    BaseAttributePtr a5 = createAttribute("version","var1", Attribute::Type::Resource);
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+
+    attrSet.insert(a2);
+    attrSet.insert(a3);
+    attrSet.insert(a4);
+    attrSet.insert(a5);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRFalse));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(05){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("r8v2","var2");
+    BaseAttributePtr a3 = createAttribute("author","va3");
+
+    BaseAttributePtr a4 = createAttribute("version","var1");
+    BaseAttributePtr a5 = createAttribute("r8v2","var2");
+    BaseAttributePtr a6 = createAttribute("author","va3");
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+
+    attrSet.insert(a4);
+    attrSet.insert(a5);
+    attrSet.insert(a6);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRTrue));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(06){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("r8v2","var2");
+    BaseAttributePtr a3 = createAttribute("author","va3");
+
+    BaseAttributePtr a4 = createAttribute("version","var2");
+    BaseAttributePtr a5 = createAttribute("r8v2","var3");
+    BaseAttributePtr a6 = createAttribute("author","va4");
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+
+    attrSet.insert(a4);
+    attrSet.insert(a5);
+    attrSet.insert(a6);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRFalse));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(07){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("r8v2","var2");
+    BaseAttributePtr a3 = createAttribute("author","va3");
+
+    BaseAttributePtr a4 = createAttribute("version","var1", Attribute::Type::Resource );
+    BaseAttributePtr a5 = createAttribute("r8v2","var2", Attribute::Type::Resource);
+    BaseAttributePtr a6 = createAttribute("author","va3", Attribute::Type::Resource);
+
+    BaseAttributePtr a7 = createAttribute("version","var2" );
+    BaseAttributePtr a8 = createAttribute("r8v2","var3");
+    BaseAttributePtr a9 = createAttribute("author","va4");
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+
+    attrSet.insert(a4);
+    attrSet.insert(a5);
+    attrSet.insert(a6);
+    attrSet.insert(a7);
+    attrSet.insert(a8);
+    attrSet.insert(a9);
+
+    //Despite that there are attribute a4,a5,a6 that matches the value of attributes
+    //a1,a2,a3 the type of the attributes is different
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRFalse));
+}
+
+//Test if the same attributes (but other instances) passes the test
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(08){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("r8v2","var2");
+    BaseAttributePtr a3 = createAttribute("author","va3");
+
+    BaseAttributePtr a4 = createAttribute("version","var1");
+    BaseAttributePtr a5 = createAttribute("r8v2","var2", Attribute::Type::Resource);
+    BaseAttributePtr a6 = createAttribute("author","va3", Attribute::Type::Resource);
+    BaseAttributePtr a7 = createAttribute("r8v2","aaa");
+    BaseAttributePtr a8 = createAttribute("author","aaa");
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+
+    attrSet.insert(a4);
+    attrSet.insert(a5);
+    attrSet.insert(a6);
+    attrSet.insert(a7);
+    attrSet.insert(a8);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRTrue));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(09){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version", NULL); //empty bag
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    attrSet.insert(a1);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRFalse));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(10){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 =  createAttribute("version","var1","var2");
+
+    BaseAttributePtr a4 =  createAttribute("version","var1");
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    attrSet.insert(a4);
+    //It's enough that one value from string bag matches
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRTrue));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(11){
+    Condition con(Condition::AND);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 =  createAttribute("version","var1","var2");
+    BaseAttributePtr a2 =  createAttribute("version","var3","var1");
+
+    BaseAttributePtr a4 =  createAttribute("version","var1");
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    attrSet.insert(a4);
+    //It's enough that one value from string bag matches
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRTrue));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(12){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 =  createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("r8v2","var2");
+    BaseAttributePtr a3 = createAttribute("author","va3");
+
+    BaseAttributePtr a4 =  createAttribute("version","var1");
+    BaseAttributePtr a5 = createAttribute("r8v2","var2", Attribute::Type::Resource);
+    BaseAttributePtr a6 = createAttribute("author","va3", Attribute::Type::Resource);
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+
+    attrSet.insert(a4);
+    attrSet.insert(a5);
+    attrSet.insert(a6);
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRTrue));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(13){
+    Condition con(Condition::AND);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 =  createAttribute("version",NULL);
+    a1->setUndetermind(true);
+    BaseAttributePtr a4 =  createAttribute("version","var1");
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a4));
+    attrSet.insert(a1);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRUndetermined));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(14){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 =  createAttribute("version",NULL);
+    a1->setUndetermind(true);
+    BaseAttributePtr a2 =  createAttribute("author","good");
+    BaseAttributePtr a4 =  createAttribute("version","var1");
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a4));
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    attrSet.insert(a1);
+    attrSet.insert(a2);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRTrue));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(15){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version",NULL,NULL);
+    a1->setUndetermind(true);
+    BaseAttributePtr a4 = createAttribute("version","var1");
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a4));
+    attrSet.insert(a1);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRUndetermined));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(16){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 =  createAttribute("version","var1","aaa");
+    a1->setUndetermind(true);
+    BaseAttributePtr a4 =  createAttribute("version","var1");
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a4));
+    attrSet.insert(a1);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRUndetermined));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(17){
+    Condition con(Condition::AND);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("version1","var1");
+    BaseAttributePtr a3 = createAttribute("version2","var1");
+    BaseAttributePtr a4 = createAttribute("version3","var1");
+    BaseAttributePtr a5 = createAttribute("version1","var2");
+
+    Condition con2(Condition::AND);
+    con2.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    Condition con3(Condition::OR);
+    con3.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+    con3.addAttribute(*DPL::StaticPointerCast<Attribute>(a4));
+
+    con.addCondition(con2);
+    con.addCondition(con3);
+
+    con.addAttribute(*DPL::StaticPointerCast<Attribute>(a4));
+    attrSet.insert(a1);
+    attrSet.insert(a3);
+    attrSet.insert(a4);
+    attrSet.insert(a5);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRFalse));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(18){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("version1","var1");
+    BaseAttributePtr a3 = createAttribute("version2","var1");
+    BaseAttributePtr a4 = createAttribute("version3","var1");
+    BaseAttributePtr a5 = createAttribute("version1","var2");
+
+    Condition con2(Condition::AND);
+    con2.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con2.addAttribute(*DPL::StaticPointerCast<Attribute>(a5));
+    Condition con3(Condition::AND);
+    con3.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+    con3.addAttribute(*DPL::StaticPointerCast<Attribute>(a4));
+    Condition con4(Condition::AND);
+    con4.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+
+    con3.addCondition(con4);
+    con.addCondition(con2);
+    con.addCondition(con3);
+
+    attrSet.insert(a1);
+    attrSet.insert(a3);
+    attrSet.insert(a4);
+    attrSet.insert(a5);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRFalse));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(19){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("version1","var1");
+    BaseAttributePtr a3 = createAttribute("version2","var1");
+    BaseAttributePtr a4 = createAttribute("version3","var1");
+    BaseAttributePtr a5 = createAttribute("version1","var2");
+
+    Condition con2(Condition::AND);
+    con2.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con2.addAttribute(*DPL::StaticPointerCast<Attribute>(a5));
+    Condition con3(Condition::OR);
+    con3.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+    con3.addAttribute(*DPL::StaticPointerCast<Attribute>(a4));
+
+    con.addCondition(con2);
+    con.addCondition(con3);
+
+    attrSet.insert(a1);
+    attrSet.insert(a3);
+    attrSet.insert(a4);
+    attrSet.insert(a5);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRTrue));
+}
+
+/*
+ * author:
+ * test: ACE Engine
+ * description: Evaluate logical condition for attributes.
+ * expect: Value should be matched properly.
+ */
+TESTSUITE03(20){
+    Condition con(Condition::OR);
+    AttributeSet attrSet;
+
+    BaseAttributePtr a1 = createAttribute("version","var1");
+    BaseAttributePtr a2 = createAttribute("version1","var1");
+    BaseAttributePtr a3 = createAttribute("version2","var1");
+    BaseAttributePtr a4 = createAttribute("version3","var1");
+
+    BaseAttributePtr a5 = createAttribute("version1","var2");
+    BaseAttributePtr a6 = createAttribute("version2","var2");
+    BaseAttributePtr a7 = createAttribute("version3","var2");
+    BaseAttributePtr a8 = createAttribute("version4","var2");
+
+    Condition con2(Condition::OR);
+    Condition con3(Condition::OR);
+    Condition con4(Condition::OR);
+    Condition con5(Condition::OR);
+
+    con2.addAttribute(*DPL::StaticPointerCast<Attribute>(a2));
+    con3.addAttribute(*DPL::StaticPointerCast<Attribute>(a3));
+    con4.addAttribute(*DPL::StaticPointerCast<Attribute>(a4));
+    con5.addAttribute(*DPL::StaticPointerCast<Attribute>(a1));
+
+    con2.addCondition(con4);
+    con3.addCondition(con5);
+    con.addCondition(con2);
+    con.addCondition(con3);
+
+    attrSet.insert(a1);
+    attrSet.insert(a5);
+    attrSet.insert(a6);
+    attrSet.insert(a7);
+    attrSet.insert(a8);
+
+    RUNNER_ASSERT(
+        evaluateResult(con,attrSet,Attribute::MatchResult::MRTrue));
+}
diff --git a/tests/ace/TestSuite04.cpp b/tests/ace/TestSuite04.cpp
new file mode 100644 (file)
index 0000000..67dad26
--- /dev/null
@@ -0,0 +1,985 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    TestSuite04.cpp
+ * @author  unknown
+ * @version 1.0
+ * @brief   Test cases for Combiner.
+ */
+
+#include <list>
+#include <string>
+#include <memory>
+
+#include <dpl/log/log.h>
+#include <dpl/test/test_runner.h>
+
+#include <ace/CombinerImpl.h>
+#include <ace/PolicySet.h>
+#include <ace/Effect.h>
+
+#define TESTSUITE04(n) \
+RUNNER_TEST(ts04_combiner_tests_ ## n)
+
+bool assertEffectEqual(Effect actual, Effect expected){
+    return (actual == expected);
+}
+
+class WTF : public CombinerImpl{
+public:
+    // the evaluation functions should be static and public
+    // but they are protected methods!
+    Effect denyOverrides(std::list<ExtendedEffect> &lst){
+        return CombinerImpl::denyOverrides(lst).getEffect();
+    }
+    Effect permitOverrides(std::list<ExtendedEffect> &lst){
+        return CombinerImpl::permitOverrides(lst).getEffect();
+    }
+    Effect firstApplicable(std::list<ExtendedEffect> &lst){
+        return CombinerImpl::firstApplicable(lst).getEffect();
+    }
+    Effect firstMatchingTarget(std::list<ExtendedEffect> &lst){
+        return CombinerImpl::firstMatchingTarget(lst).getEffect();
+    }
+};
+
+Effect denyOverridesTest(std::list<ExtendedEffect> &lst) {
+    WTF impl;
+    return impl.denyOverrides(lst);
+}
+
+Effect permitOverridesTest(std::list<ExtendedEffect> &lst) {
+    WTF impl;
+    return impl.permitOverrides(lst);
+}
+
+Effect firstApplicableTest(std::list<ExtendedEffect> &lst) {
+    WTF impl;
+    return impl.firstApplicable(lst);
+}
+
+Effect firstMatchingTargetTest(std::list<ExtendedEffect> &lst) {
+    WTF impl;
+    return impl.firstMatchingTarget(lst);
+}
+
+RUNNER_TEST_GROUP_INIT(ACE_TEST_SUITE_04)
+
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effects Deny,
+ * Undetermined, Permit, Inapplicable
+ * expect: evaluation of effect list to Deny
+ */
+TESTSUITE04(00_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Deny));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effects
+ * Undetermined, Permit, Inapplicable, Deny, Permit
+ * expect: evaluation of effect list to Deny
+ */
+TESTSUITE04(01_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Undetermined);
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Deny);
+    effectList.push_back(Permit);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Deny));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effects
+ * Undetermined, Permit, Inapplicable, Permit
+ * expect: evaluation of effect list to Undetermined
+ */
+TESTSUITE04(02_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Undetermined);
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Permit);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Undetermined));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effects
+ * Permit, Inapplicable, Permit, Undetermined, PromptSession
+ * expect: evaluation of effect list to Undetermined
+ */
+TESTSUITE04(03_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Permit);
+    effectList.push_back(Undetermined);
+    effectList.push_back(PromptSession);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Undetermined));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effects
+ * Permit, Inapplicable, Permit, PromptOneShot, PromptSession, PromptBlanket
+ * expect: evaluation of effect list to PromptOneShot
+ */
+TESTSUITE04(04_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Permit);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, PromptOneShot));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effects
+ * Permit, Inapplicable, Permit, PromptSession, PromptBlanket
+ * expect: evaluation of effect list to PromptSession
+ */
+TESTSUITE04(05_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Permit);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, PromptSession));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effects
+ * Permit, Inapplicable, Permit, PromptBlanket
+ * expect: evaluation of effect list to PromptBlanket
+ */
+TESTSUITE04(06_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Permit);
+    effectList.push_back(PromptBlanket);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, PromptBlanket));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effects
+ * Permit, Inapplicable, Permit
+ * expect: evaluation of effect list to Permit
+ */
+TESTSUITE04(07_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Permit);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Permit));
+}
+
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining one element
+ * effects list with Inapplicable
+ * expect: evaluation of effect list to Inapplicable
+ */
+TESTSUITE04(08_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Inapplicable);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Inapplicable));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining empty effect list
+ * expect: evaluation of effect list to Inapplicable
+ */
+TESTSUITE04(09_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Inapplicable));
+}
+
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effect list
+ * Deny, Undetermined, Permit, Error, Inapplicable
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(10_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Permit);
+    effectList.push_back(Error);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effect list
+ * Error, Undetermined, Error, Inapplicable, Permit
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(11_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Error);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Error);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Permit);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effect list
+ * Permit, Inapplicable, Permit, Error, PromptOneShot, PromptSession,
+ * PromptBlanket
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(12_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Permit);
+    effectList.push_back(Error);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effect list
+ * Permit, Inapplicable, Permit, Error, PromptBlanket,
+ * PromptSession
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(13_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Permit);
+    effectList.push_back(Error);
+    effectList.push_back(PromptBlanket);
+    effectList.push_back(PromptSession);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effect list
+ * Error, Inapplicable
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(14_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Error);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "denyOverrides" for combining effect list
+ * Inapplicable, Error
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(15_denyOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Error);
+
+    Effect eff = denyOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining effect list
+ * Deny, Undetermined, Permit, Inapplicable, PromptOneShot, PromptSession,
+ * PromptBlanket
+ * expect: evaluation of effect list to Permit
+ */
+TESTSUITE04(16_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Permit));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining effect list
+ * Deny, Inapplicable, PromptOneShot, PromptSession, PromptBlanket, Undetermined
+ * expect: evaluation of effect list to Undetermined
+ */
+TESTSUITE04(17_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+    effectList.push_back(Undetermined);
+
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Undetermined));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining effect list
+ * Deny, Inapplicable, PromptOneShot, PromptSession, PromptBlanket
+ * expect: evaluation of effect list to PromptBlanket
+ */
+TESTSUITE04(18_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+
+
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, PromptBlanket));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining effect list
+ * Deny, PromptOneShot, PromptSession, Inapplicable
+ * expect: evaluation of effect list to PromptSession
+ */
+TESTSUITE04(19_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptSession);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, PromptSession));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining effect list
+ * Deny, Inapplicable, PromptOneShot
+ * expect: evaluation of effect list to PromptOneShot
+ */
+TESTSUITE04(20_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(PromptOneShot);
+
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, PromptOneShot));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining effect list
+ * Deny, Inapplicable
+ * expect: evaluation of effect list to Deny
+ */
+TESTSUITE04(21_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Deny));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining one element
+ * effect list with Inapplicable
+ * expect: evaluation of effect list to Inapplicable
+ */
+TESTSUITE04(22_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Inapplicable);
+
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Inapplicable));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining empty effect
+ * list
+ * expect: evaluation of effect list to Inapplicable
+ */
+TESTSUITE04(23_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Inapplicable));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining effect list
+ * Deny, Undetermined, Permit, Inapplicable, Error, PromptSession,
+ * PromptOneShot, PromptBlanket
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(24_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Permit);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Error);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptBlanket);
+
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining effect list
+ * Deny, Inapplicable, Error, PromptOneShot, PromptSession, PromptBlanket,
+ * Undetermined, Error
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(25_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Error);
+
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining effect list
+ * Deny, Error, Inapplicable, PromptOneShot
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(26_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Error);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(PromptOneShot);
+
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "permitOverrides" for combining one element
+ * effect list with Error
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(27_permitOverrides){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Error);
+    Effect eff = permitOverridesTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstApplicable" for combining effect list
+ * Deny, Inapplicable, PromptOneShot, PromptSession, PromptBlanket, Undetermined
+ * expect: evaluation of effect list to Deny
+ */
+TESTSUITE04(28_firstApplicable){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+    effectList.push_back(Undetermined);
+
+    Effect eff = firstApplicableTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Deny));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstApplicable" for combining effect list
+ * Undetermined, Deny, PromptOneShot, Inapplicable, PromptOneShot,
+ * PromptSession, PromptBlanket, Undetermined
+ * expect: evaluation of effect list to Undetermined
+ */
+TESTSUITE04(29_firstApplicable){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Undetermined);
+    effectList.push_back(Deny);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+    effectList.push_back(Undetermined);
+
+    Effect eff = firstApplicableTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Undetermined));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstApplicable" for combining effect list
+ * Inapplicable, Deny, PromptOneShot, Inapplicable, PromptOneShot,
+ * PromptSession, PromptBlanket, Undetermined
+ * expect: evaluation of effect list to Deny
+ */
+TESTSUITE04(30_firstApplicable){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Deny);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+    effectList.push_back(Undetermined);
+
+    Effect eff = firstApplicableTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Deny));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstApplicable" for combining effect list
+ * Inapplicable, Undetermined, PromptOneShot, Inapplicable, PromptOneShot,
+ * PromptSession, PromptBlanket, Undetermined
+ * expect: evaluation of effect list to Undetermined
+ */
+TESTSUITE04(31_firstApplicable){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Undetermined);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+    effectList.push_back(Undetermined);
+
+    Effect eff = firstApplicableTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Undetermined));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstApplicable" for combining effect list
+ * Inapplicable, Inapplicable, Inapplicable
+ * expect: evaluation of effect list to Inapplicable
+ */
+TESTSUITE04(32_firstApplicable){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = firstApplicableTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Inapplicable));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstApplicable" for combining effect list
+ * Inapplicable, Inapplicable, Inapplicable, Permit
+ * expect: evaluation of effect list to Permit
+ */
+TESTSUITE04(33_firstApplicable){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Permit);
+
+    Effect eff = firstApplicableTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Permit));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstApplicable" for combining empty effect
+ * list
+ * expect: evaluation of effect list to Inapplicable
+ */
+TESTSUITE04(34_firstApplicable){
+    std::list<ExtendedEffect> effectList;
+
+    Effect eff = firstApplicableTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Inapplicable));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstApplicable" for combining effect list
+ * Deny, Inapplicable, PromptOneShot, Error, PromptSession, PromptBlanket,
+ * Undetermined
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(35_firstApplicable){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(Error);
+    effectList.push_back(PromptSession);
+    effectList.push_back(PromptBlanket);
+    effectList.push_back(Undetermined);
+
+    Effect eff = firstApplicableTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstApplicable" for combining effect list
+ * Inapplicable, Inapplicable, Inapplicable, Error, Permit
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(36_firstApplicable){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Error);
+    effectList.push_back(Permit);
+
+    Effect eff = firstApplicableTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstApplicable" for combining one element
+ * effect list with Error
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(37_firstApplicable){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Error);
+
+    Effect eff = firstApplicableTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstMatching" for combining effect list
+ * Inapplicable, Deny, PromptOneShot, Inapplicable
+ * expect: evaluation of effect list to Inapplicable
+ */
+TESTSUITE04(38_firstMatching){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Deny);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = firstMatchingTargetTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Inapplicable));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstMatching" for combining effect list
+ * Undetermined, Deny, PromptOneShot, Inapplicable
+ * expect: evaluation of effect list to Undetermined
+ */
+TESTSUITE04(39_firstMatching){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Undetermined);
+    effectList.push_back(Deny);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = firstMatchingTargetTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Undetermined));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstMatching" for combining effect list
+ * Deny, Inapplicable
+ * expect: evaluation of effect list to Deny
+ */
+TESTSUITE04(39a_firstMatching){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Deny);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = firstMatchingTargetTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Deny));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstMatching" for combining one element
+ * effect list with Permit
+ * expect: evaluation of effect list to Permit
+ */
+TESTSUITE04(39b_firstMatching){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Permit);
+
+    Effect eff = firstMatchingTargetTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Permit));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstMatching" for combining effect list
+ * Undetermined, Undetermined, Undetermined
+ * expect: evaluation of effect list to Undetermined
+ */
+TESTSUITE04(40_firstMatching){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Undetermined);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Undetermined);
+
+    Effect eff = firstMatchingTargetTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Undetermined));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstMatching" for combining empty effect list
+ * expect: evaluation of effect list to Inapplicable
+ */
+TESTSUITE04(41_firstMatching){
+    std::list<ExtendedEffect> effectList;
+
+    Effect eff = firstMatchingTargetTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Inapplicable));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstMatching" for combining one element
+ * effect list with Inapplicable
+ * expect: evaluation of effect list to Inapplicable
+ */
+TESTSUITE04(42_firstMatching){
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Inapplicable);
+
+    Effect eff = firstMatchingTargetTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Inapplicable));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstMatching" for combining effect list
+ * Undetermined, Undetermined, Undetermined, Deny, Inapplicable, Undetermined,
+ * Deny, PromptOneShot, Inapplicable
+ * expect: evaluation of effect list to Undetermined
+ */
+TESTSUITE04(43_firstMatching){
+
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Undetermined);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Deny);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Deny);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = firstMatchingTargetTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Undetermined));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstMatching" for combining effect list
+ * Inapplicable, Deny, PromptOneShot, Error, Inapplicable
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(44_firstMatching){
+
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Deny);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(Error);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = firstMatchingTargetTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstMatching" for combining effect list
+ * Undetermined, Undetermined, Error, Undetermined, Deny, Inapplicable,
+ * Undetermined, Deny, PromptOneShot, Inapplicable
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(45_firstMatching){
+
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Undetermined);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Error);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Deny);
+    effectList.push_back(Inapplicable);
+    effectList.push_back(Undetermined);
+    effectList.push_back(Deny);
+    effectList.push_back(PromptOneShot);
+    effectList.push_back(Inapplicable);
+
+    Effect eff = firstMatchingTargetTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: Tested algorithm "firstMatching" for combining one element
+ * effect list with Error
+ * expect: evaluation of effect list to Error
+ */
+TESTSUITE04(46_firstMatching){
+
+    std::list<ExtendedEffect> effectList;
+    effectList.push_back(Error);
+
+    Effect eff = firstMatchingTargetTest(effectList);
+    RUNNER_ASSERT(assertEffectEqual(eff, Error));
+}
diff --git a/tests/ace/TestSuite05.cpp b/tests/ace/TestSuite05.cpp
new file mode 100644 (file)
index 0000000..853348b
--- /dev/null
@@ -0,0 +1,1014 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    TestSuite05.cpp
+ * @author  unknown
+ * @version 1.0
+ * @brief   Test cases for Attribute class.
+ */
+
+#include <iostream>
+#include <list>
+#include <set>
+#include <string>
+#include <memory>
+
+#include <dpl/test/test_runner.h>
+
+#include <ace/Attribute.h>
+#include <ace-dao-ro/BaseAttribute.h>
+
+#define TESTSUITE05(n) \
+RUNNER_TEST(ts05_attr_tests_ ## n)
+
+class AT : public Attribute {
+public:
+    AT(std::string nm)
+      : Attribute(nm)
+    {}
+
+    static std::string* uriAuthorityStatic(const std::string *input) {
+        AT at("Micky");
+        return at.uriAuthority(input);
+    }
+
+    static std::string* uriHostStatic(const std::string *input) {
+        AT at("Pluto");
+        return at.uriHost(input);
+    }
+
+    static std::string* uriSchemeStatic(const std::string *input) {
+        AT at("Donald");
+        return at.uriScheme(input);
+    }
+
+    static std::string* uriSchemeAuthorityStatic(const std::string *input) {
+        AT at("Winnie the Pooh");
+        return at.uriSchemeAuthority(input);
+    }
+
+    static std::string* uriPathStatic(const std::string *input) {
+        AT at("Hannibal");
+        return at.uriPath(input);
+    }
+
+    static bool markTest(){
+        bool result = true;
+        for(int i =0; i<128; ++i){
+            if( i == '-' || i == '_' || i == '.'|| i == '!'|| i == '~' || i == '*' || i == '\'' || i == ')' || i == '(' ){
+                if (!mark[i]){
+                    result = false;
+                    break;
+                }
+            }
+            else{
+                if(mark[i]){
+                    result =false;
+                    break;
+                }
+            }
+        }
+        return result;
+    }
+
+    static bool digitTest(){
+        bool result = true;
+        for(int i =0; i<128; ++i){
+            if( i > 47 && i < 58 ){
+                if (!digit[i]){
+                    result = false;
+                    break;
+                }
+            }
+            else{
+                if(digit[i]){
+                    result =false;
+                    break;
+                }
+            }
+        }
+        return result;
+    }
+
+    static bool alphaTest(){
+        bool result = true;
+        for(int i =0; i<128; ++i){
+            if( ( i>64 && i<91 ) || ( i>96 && i<123  ) ) {
+                if (!alpha[i]){
+                    result = false;
+                    break;
+                }
+            }
+            else{
+                if(alpha[i]){
+                    result =false;
+                    break;
+                }
+            }
+        }
+        return result;
+    }
+
+    static bool isEscapedStatic(const char esc[3]) {
+        AT at("Swinka");
+        return at.isEscaped(esc);
+    }
+};
+
+bool assertEqual(const std::string * actual, const char * intended) {
+    if (actual == NULL || intended == NULL) {
+        if (intended == NULL && actual == NULL) {
+            return true;
+        }
+        else {
+            return false;
+        }
+    }
+
+    std::string temp(intended);
+
+    if (temp == *actual) {
+        return true;
+    }
+    else {
+        return false;
+    }
+}
+
+bool assertTrue(bool condition){
+    return condition;
+}
+
+bool assertFalse(bool condition){
+    return !condition;
+}
+
+RUNNER_TEST_GROUP_INIT(ACE_TEST_SUITE_05)
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://www.wp.pl" argument
+ * expect: "www.wp.pl"
+ */
+TESTSUITE05(01_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://www.wp.pl");
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "www.wp.pl"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://authority?path/asdf" argument
+ * expect: "authority"
+ */
+TESTSUITE05(02_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://authority?path/asdf");
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "authority"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "abcd" argument
+ * expect: ""
+ */
+TESTSUITE05(03_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("abcd"); //This should be interpreted as schema
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), ""));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://authority/asdf" argument
+ * expect: "authority"
+ */
+TESTSUITE05(04_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://authority/asdf");
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "authority"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://user@host:20?ds" argument
+ * expect: "user@host:20"
+ */
+TESTSUITE05(05_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://user@host:20?ds");
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "user@host:20"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://hostname:23" argument
+ * expect: "hostname:23"
+ */
+TESTSUITE05(06_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://hostname:23");
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "hostname:23"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://hostname:23" argument
+ * expect: "hostname:23"
+ */
+TESTSUITE05(07_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://user@host:port");
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "user@host:port"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://1user@host:port" argument
+ * expect: "1user@host:port"
+ */
+TESTSUITE05(08_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://1user@host:port"); //This is a VALID URI
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "1user@host:port"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://abc%30" argument
+ * expect: "abc%30"
+ */
+TESTSUITE05(09_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://abc%30"); //This is not a valid uri
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "abc%30"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http:///asd" argument (not a valid URI)
+ * expect: ""
+ */
+TESTSUITE05(10_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http:///asd"); //This is not a valid uri
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), ""));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://?asd" argument (not a valid URI)
+ * expect: ""
+ */
+TESTSUITE05(11_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://?asd"); //This is not a valid uri
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), ""));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://%34%56%67%ab" argument
+ * expect: "%34%56%67%ab"
+ */
+TESTSUITE05(12_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://%34%56%67%ab");
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "%34%56%67%ab"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://<>" argument (not a valid URI)
+ * expect: NULL
+ */
+TESTSUITE05(13_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://<>"); //This is not a valid uri
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), NULL));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriAuthority method of Attribute class on
+ * "http://\\/" argument (not a valid URI)
+ * expect: NULL
+ */
+TESTSUITE05(14_uriAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://\\/"); //This is not a valid uri
+    outcome.reset(AT::uriAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), NULL));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "http://user@host:23" argument
+ * expect: "host"
+ */
+TESTSUITE05(15_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://user@host:23");
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "host"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "http://user@host:name" argument (not a valid URI)
+ * expect: ""
+ */
+TESTSUITE05(16_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://user@host:name"); //This is not a valid uri
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), ""));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "http::::" argument (not a valid URI)
+ * expect: ""
+ */
+TESTSUITE05(17_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http::::"); //This is a valid uri
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), ""));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "..%%%." argument (not a valid URI)
+ * expect: NULL
+ */
+TESTSUITE05(18_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("..%%%."); //This is not a valid uri
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), NULL));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "ftp://abds.eu/fda" argument
+ * expect: "abds.eu"
+ */
+TESTSUITE05(19_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp://abds.eu/fda");
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "abds.eu"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "abs%14ccc" argument
+ * expect: ""
+ */
+TESTSUITE05(20_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("abs%14ccc");
+    //This is a valid uri because it's interpreted as a path not a host
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), ""));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "http://abc@123.2.23.213:982" argument
+ * expect: "123.2.23.213"
+ */
+TESTSUITE05(21_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://abc@123.2.23.213:982");
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "123.2.23.213"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "http://abc@1233.2.23.213:982" argument
+ * expect: ""
+ */
+TESTSUITE05(22_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://abc@1233.2.23.213:982");
+    //Hostname is invalid, but uri is valid
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), ""));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "http://ab%23c@host" argument
+ * expect: "host"
+ */
+TESTSUITE05(23_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://ab%23c@host"); //Valid escaped characters
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "host"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "http://ab%23c@host%34" argument
+ * expect: ""
+ */
+TESTSUITE05(24_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://ab%23c@host%34"); //Invalid escaped characters in hostname
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), ""));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "http://ab%GGc@host" argument
+ * expect: NULL
+ */
+TESTSUITE05(25_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://ab%GGc@host"); //Wrong character %
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), NULL));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriHost method of Attribute class on
+ * "http://www.example.pl" argument
+ * expect: "www.example.pl"
+ */
+TESTSUITE05(26_uriHost){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://www.example.pl");
+    outcome.reset(AT::uriHostStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "www.example.pl"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriScheme method of Attribute class on
+ * "http://host" argument
+ * expect: "http"
+ */
+TESTSUITE05(27_uriScheme){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://host");
+    outcome.reset(AT::uriSchemeStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "http"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriScheme method of Attribute class on
+ * "1http://host" argument
+ * expect: NULL
+ */
+TESTSUITE05(28_uriScheme){
+    std::unique_ptr<std::string> outcome;
+    //Wrong character '1' in scheme , it's not an URI because two slashes are not acceptable
+    //in any other place than in separation between scheme and pat
+    std::string query("1http://host");
+    outcome.reset(AT::uriSchemeStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), NULL));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriScheme method of Attribute class on
+ * "ftp+a-fdf.ads://host" argument
+ * expect: "ftp+a-fdf.ads"
+ */
+TESTSUITE05(29_uriScheme){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp+a-fdf.ads://host");
+    outcome.reset(AT::uriSchemeStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "ftp+a-fdf.ads"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriScheme method of Attribute class on
+ * "+++://host" argument
+ * expect: NULL
+ */
+TESTSUITE05(30_uriScheme){
+    std::unique_ptr<std::string> outcome;
+    //Scheme cannot start with plus, it's not an URI because two slashes are not acceptable
+    //in any other place than in separation between scheme and path
+    std::string query("+++://host");
+    outcome.reset(AT::uriSchemeStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), NULL));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriScheme method of Attribute class on
+ * "aaaac" argument
+ * expect: ""
+ */
+TESTSUITE05(31_uriScheme){
+    std::unique_ptr<std::string> outcome;
+    std::string query("aaaac"); //It's a path not a scheme'a
+    outcome.reset(AT::uriSchemeStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), ""));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriScheme method of Attribute class on
+ * "ftpa%34fdfads://host" argument
+ * expect: NULL
+ */
+TESTSUITE05(32_uriScheme){
+    std::unique_ptr<std::string> outcome;
+    //no escaped characters in schema, it's not an URI because two slashes are not acceptable
+    //in any other place than in separation between scheme and path
+    std::string query("ftpa%34fdfads://host");
+    outcome.reset(AT::uriSchemeStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), NULL));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriScheme method of Attribute class on
+ * "meaninglessstring://host%34" argument
+ * expect: "meaninglessstring"
+ */
+TESTSUITE05(33_uriScheme){
+    std::unique_ptr<std::string> outcome;
+    //no escaped characters in schema, it's not an URI because two slashes are not acceptable
+    //in any other place than in separation between scheme and path
+    std::string query("meaninglessstring://host%34");
+    outcome.reset(AT::uriSchemeStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "meaninglessstring"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriScheme method of Attribute class on
+ * "meaninglessstring2://" argument
+ * expect: "meaninglessstring2"
+ */
+TESTSUITE05(34_uriScheme){
+    std::unique_ptr<std::string> outcome;
+    std::string query("meaninglessstring2://");
+    outcome.reset(AT::uriSchemeStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "meaninglessstring2"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriScheme method of Attribute class on
+ * "http://www.samsung.com/ace/bondi#5" argument
+ * expect: "http"
+ */
+TESTSUITE05(35_uriScheme){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://www.samsung.com/ace/bondi#5");
+    outcome.reset(AT::uriSchemeStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "http"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriScheme method of Attribute class on
+ * "www.samsung.com" argument
+ * expect: ""
+ */
+TESTSUITE05(36_uriScheme){
+    std::unique_ptr<std::string> outcome;
+    std::string query("www.samsung.com");
+    outcome.reset(AT::uriSchemeStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), ""));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriSchemeAuthority method of Attribute class on
+ * "http://www.samsung.com" argument
+ * expect: "http://www.samsung.com"
+ */
+TESTSUITE05(37_uriSchemeAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://www.samsung.com");
+    outcome.reset(AT::uriSchemeAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "http://www.samsung.com"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriSchemeAuthority method of Attribute class on
+ * "ftp23://www.samsung.com/avc%23" argument
+ * expect: "ftp23://www.samsung.com"
+ */
+TESTSUITE05(38_uriSchemeAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp23://www.samsung.com/avc%23");
+    outcome.reset(AT::uriSchemeAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "ftp23://www.samsung.com"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriSchemeAuthority method of Attribute class on
+ * "ftp++://anonymous@hostname:12/avc%23" argument
+ * expect: "ftp++://anonymous@hostname:12"
+ */
+TESTSUITE05(39_uriSchemeAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp++://anonymous@hostname:12/avc%23");
+    outcome.reset(AT::uriSchemeAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "ftp++://anonymous@hostname:12"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriSchemeAuthority method of Attribute class on
+ * "32ftp://anonymous@hostname:12/avc%23" argument
+ * expect: NULL
+ */
+TESTSUITE05(40_uriSchemeAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("32ftp://anonymous@hostname:12/avc%23");
+    outcome.reset(AT::uriSchemeAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), NULL));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriSchemeAuthority method of Attribute class on
+ * "http://aaabbb?acd" argument
+ * expect: "http://aaabbb"
+ */
+TESTSUITE05(41_uriSchemeAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://aaabbb?acd");
+    outcome.reset(AT::uriSchemeAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "http://aaabbb"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriSchemeAuthority method of Attribute class on
+ * "http://aaabbb/acd;sdf;sdf" argument
+ * expect: "http://aaabbb"
+ */
+TESTSUITE05(42_uriSchemeAuthority){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://aaabbb/acd;sdf;sdf");
+    outcome.reset(AT::uriSchemeAuthorityStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "http://aaabbb"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriPath method of Attribute class on
+ * "ftp://authority//invalidpath" argument
+ * expect: NULL
+ */
+TESTSUITE05(43_uriPath){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp://authority//invalidpath");
+    outcome.reset(AT::uriPathStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), NULL));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriPath method of Attribute class on
+ * "ftp://authority/validpath" argument
+ * expect: "validpath"
+ */
+TESTSUITE05(44_uriPath){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp://authority/validpath");
+    outcome.reset(AT::uriPathStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "validpath"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriPath method of Attribute class on
+ * "ftp://authority/validpath;param;param" argument
+ * expect: "validpath;param;param"
+ */
+TESTSUITE05(45_uriPath){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp://authority/validpath;param;param");
+    outcome.reset(AT::uriPathStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "validpath;param;param"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriPath method of Attribute class on
+ * "ftp://authority/validpath;param;param?query" argument
+ * expect: "validpath;param;param"
+ */
+TESTSUITE05(46_uriPath){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp://authority/validpath;param;param?query");
+    outcome.reset(AT::uriPathStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "validpath;param;param"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriPath method of Attribute class on
+ * "ftp://authority/validpath;?param;param?query" argument
+ * expect: "validpath;"
+ */
+TESTSUITE05(47_uriPath){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp://authority/validpath;?param;param?query");
+    outcome.reset(AT::uriPathStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "validpath;"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriPath method of Attribute class on
+ * "ftp://authority/validpath;param?;param?query" argument
+ * expect: "validpath;param"
+ */
+TESTSUITE05(48_uriPath){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp://authority/validpath;param?;param?query");
+    outcome.reset(AT::uriPathStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "validpath;param"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriPath method of Attribute class on
+ * "ftp://authority/valid:path?query" argument
+ * expect: "valid:path"
+ */
+TESTSUITE05(49_uriPath){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp://authority/valid:path?query");
+    outcome.reset(AT::uriPathStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "valid:path"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriPath method of Attribute class on
+ * "ftp://authority/:::" argument
+ * expect: ":::"
+ */
+TESTSUITE05(50_uriPath){
+    std::unique_ptr<std::string> outcome;
+    std::string query("ftp://authority/:::");
+    outcome.reset(AT::uriPathStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), ":::"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriPath method of Attribute class on
+ * "/path1/path2?abc#fragment" argument
+ * expect: "path1/path2"
+ */
+TESTSUITE05(51_uriPath){
+    std::unique_ptr<std::string> outcome;
+    std::string query("/path1/path2?abc#fragment");
+    outcome.reset(AT::uriPathStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "path1/path2"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing uriPath method of Attribute class on
+ * "http://www.samsung.com/normalpath/path2?query" argument
+ * expect: "normalpath/path2"
+ */
+TESTSUITE05(52_uriPath){
+    std::unique_ptr<std::string> outcome;
+    std::string query("http://www.samsung.com/normalpath/path2?query");
+    outcome.reset(AT::uriPathStatic(&query));
+    RUNNER_ASSERT(assertEqual(outcome.get(), "normalpath/path2"));
+
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing if "mark" static table in Attribute class contains
+ * "true" on indices for characters -_.!~*')(
+ * expect: true
+ */
+TESTSUITE05(53_markTest){
+    RUNNER_ASSERT(AT::markTest());
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing if "digit" static table in Attribute class contains
+ * "true" on indices for characters that are digits
+ * expect: true
+ */
+TESTSUITE05(54_digitTest){
+    RUNNER_ASSERT(AT::digitTest());
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: testing if "digit" static table in Attribute class contains
+ * "true" on indices for characters that are real characters (letters)
+ * expect: true
+ */
+TESTSUITE05(55_alphaTest){
+    RUNNER_ASSERT(AT::alphaTest());
+}
+
+/*
+ * author: unknown
+ * test: ACE Engine
+ * description: checking Attribute isEscapedStatic method of Attribute class
+ * expect: true, true, false, false, false, false, true, true
+ */
+TESTSUITE05(56_escapedTest){
+    const char * query = "%23";
+    RUNNER_ASSERT(assertTrue(AT::isEscapedStatic(query)));
+    query = "%ab";
+    RUNNER_ASSERT(assertTrue(AT::isEscapedStatic(query)));
+
+    query = "%a";
+    RUNNER_ASSERT(assertFalse(AT::isEscapedStatic(query)));
+
+    query = "%rw";
+    RUNNER_ASSERT(assertFalse(AT::isEscapedStatic(query)));
+
+    query = NULL;
+    RUNNER_ASSERT(assertFalse(AT::isEscapedStatic(query)));
+
+    query = "abc";
+    RUNNER_ASSERT(assertFalse(AT::isEscapedStatic(query)));
+
+    query = "%bc";
+    RUNNER_ASSERT(assertTrue(AT::isEscapedStatic(query)));
+
+    query = "%DF";
+    RUNNER_ASSERT(assertTrue(AT::isEscapedStatic(query)));
+}
+
diff --git a/tests/ace/TestSuite06.cpp b/tests/ace/TestSuite06.cpp
new file mode 100644 (file)
index 0000000..68b95c1
--- /dev/null
@@ -0,0 +1,1653 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    TestSuite06.cpp
+ * @author  unknown
+ * @version 1.0
+ * @brief   Test cases for AceDAO implementation.
+ */
+#include <iostream>
+#include <string>
+#include <memory>
+
+#include <dpl/foreach.h>
+#include <dpl/test/test_runner.h>
+
+#include <ace-dao-rw/AceDAO.h>
+#include <ace/Attribute.h>
+#include <ace/Preference.h>
+#include <ace/SettingsLogic.h>
+
+#define TEST_WIDGET_HANDLE  23
+
+#define TESTSUITE06(n) \
+RUNNER_TEST(ts06_ace_dao_ ## n)
+
+#define CLEANENV \
+    do{                                              \
+        AceDB::AceDAO::clearWidgetDevCapSettings();  \
+        AceDB::AceDAO::clearDevCapSettings();        \
+    }while(0)
+
+using namespace AceDB;
+
+int operator==(const Attribute& left, const Attribute& right)
+{
+   return ( (*left.getName() == *right.getName()));
+}
+
+bool UserSettingsAgreed(std::list<PermissionTriple>* expected,
+                        std::list<PermissionTriple>* allRules)
+{
+    if (allRules->empty() && expected->empty())
+    {
+        return true;
+    }
+
+    std::list<PermissionTriple>::iterator itA;
+    FOREACH(itE, *expected)
+    {
+        if (itE->devCap.empty()){
+            return false;  //some error occur
+        }
+
+        for (itA = allRules->begin(); itA !=  allRules->end(); ++itA){
+            if (itA->appId == itE->appId &&
+                itA->devCap == itE->devCap)
+            {
+                if (itA->access == itE->access){
+                    break;
+                }
+                else{
+                    return false; //optimization
+                }
+            }
+        }
+
+        if (itA == allRules->end())
+        {
+            if (itE->access == Preference::PREFERENCE_DEFAULT)
+            {  // this value is not set in DB
+                continue;
+            }
+            //if we are here -it means that expected values doesnt exist in DB
+            return false;
+        }
+        else
+        {
+            continue;   //go to next expected attr
+        }
+    }
+
+    //it means that all required values exist in DB
+    return true;
+}
+
+
+bool UserSettingNotStored(std::list<PermissionTriple>* userSettings,
+                          std::string res,
+                          WidgetHandle handler,
+                          Preference pref)
+{
+    if (userSettings->empty())
+    {
+        return true;
+    }
+
+    FOREACH(iter, *userSettings)
+    {
+        if (iter->appId == handler && iter->devCap == res){
+            if (iter->access == pref){
+                return false;  //this value has been saved
+            }
+            else{
+                continue;  //value has been saved
+            }
+        }
+    }
+
+    return true;
+}
+
+
+
+bool ResourceSettingsAgreed(
+        std::list< std::pair<const std::string*,Preference> > *expected,
+        std::map<std::string, Preference>* allRules)
+{
+    std::list< std::pair<const std::string*,Preference> >::iterator itE;
+    std::map<std::string, Preference>::iterator itA;
+
+    FOREACH(itE, *expected)
+    {
+        itA = allRules->find(*(itE->first));
+        if (itA != allRules->end() && itA->second == itE->second)
+        {
+            continue;
+        }
+        else
+        {
+            return false;
+        }
+    }
+
+    return true;
+}
+
+bool ResourceSettingsEqual(
+        std::list< std::pair<const std::string*,Preference> > * actual,
+        std::map<std::string, Preference>* expected)
+{
+    bool flag = false;
+    FOREACH(iterA, *actual)
+    {
+        FOREACH(iterE, *expected)
+        {
+            if (*(iterA->first) == iterE->first &&
+                iterA->second == iterE->second)
+            {
+                flag = true;
+            }
+        }
+        if (!flag)
+        {
+            return false;
+        }
+        flag = false;
+    }
+
+    return true;
+}
+
+//bool VSPAssertEqual(Verdict actual, Verdict expected){
+//    return (actual == expected);
+//}
+
+
+bool AttributeEqual(AttributeSet  actual, AttributeSet expected){
+    return (actual == expected);
+}
+
+bool ResourceSettingEqual(std::map<std::string, Preference>*  rSettings,
+                          std::string res,
+                          Preference pref)
+{
+    std::map<std::string, Preference>::iterator iter = rSettings->find(res);
+
+    if (iter != rSettings->end() && iter->second ==pref)
+    {
+        return true;
+    }
+
+    return false;
+}
+
+
+bool  UserSettingEqual(std::list<PermissionTriple>* userSettings,
+                       std::string res,
+                       WidgetHandle handler,
+                       Preference pref)
+{
+        if (userSettings->empty() && pref == Preference::PREFERENCE_DEFAULT)
+        {
+            return true;
+        }
+        FOREACH(iter, *userSettings)
+        {
+            if (iter->devCap.empty())
+            {
+                return false; //some error occurred
+            }
+            if (iter->appId == handler && iter->devCap == res){
+                if (iter->access == pref)
+                {
+                    return true;
+                }
+                else
+                {
+                    return false;
+                }
+            }
+        }
+
+    return false;
+}
+
+RUNNER_TEST_GROUP_INIT(ACE_TEST_SUITE_06)
+
+//Test does  verdict PERMIT is saved when validity is once
+TESTSUITE06(01){
+    CLEANENV;
+    AttributeSet attributeSet;
+    std::string tmp("atrS");
+    std::string tmpValue("Buu");
+    BaseAttributePtr atr(new Attribute(&tmp,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+    attributeSet.insert(atr);
+
+    AceDAO::setPolicyResult(attributeSet,
+                            ExtendedPolicyResult(PolicyEffect::PERMIT));
+    OptionalExtendedPolicyResult opt =
+        AceDAO::getPolicyResult(attributeSet);
+
+    PolicyResult effect(PolicyEffect::DENY);
+    if (!opt.IsNull()) {
+        effect = opt->policyResult;
+    }
+
+    RUNNER_ASSERT(effect == PolicyEffect::PERMIT);
+}
+
+TESTSUITE06(02){
+    CLEANENV;
+    AttributeSet attributeSet;
+    std::string tmp("atrS");
+    std::string tmpValue("Buu");
+    BaseAttributePtr atr(new Attribute(&tmp,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+    attributeSet.insert(atr);
+
+    AceDAO::setPolicyResult(attributeSet,
+                            ExtendedPolicyResult(PolicyEffect::DENY));
+    OptionalExtendedPolicyResult opt = AceDAO::getPolicyResult(attributeSet);
+
+    PolicyResult effect(PolicyEffect::PERMIT);
+    if (!opt.IsNull()) {
+        effect = opt->policyResult;
+    }
+
+    RUNNER_ASSERT(effect == PolicyEffect::DENY);
+}
+
+TESTSUITE06(03){
+    CLEANENV;
+    AttributeSet attributeSet;
+    std::string tmp("atrS");
+    std::string tmpValue("Buu");
+    BaseAttributePtr atr(new Attribute(&tmp,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+    attributeSet.insert(atr);
+
+    AceDAO::setPolicyResult(attributeSet,
+                            ExtendedPolicyResult(PolicyEffect::PROMPT_ONESHOT));
+    OptionalExtendedPolicyResult opt = AceDAO::getPolicyResult(attributeSet);
+
+    PolicyResult effect(PolicyEffect::DENY);
+    if (!opt.IsNull()) {
+        effect = opt->policyResult;
+    }
+
+    RUNNER_ASSERT(effect == PolicyEffect::PROMPT_ONESHOT);
+}
+
+TESTSUITE06(04){
+    CLEANENV;
+    AttributeSet attributeSet;
+    std::string tmp("atrS");
+    std::string tmpValue("Buu");
+    BaseAttributePtr atr(new Attribute(&tmp,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+    attributeSet.insert(atr);
+
+    AceDAO::setPolicyResult(attributeSet,
+                            ExtendedPolicyResult(PolicyEffect::PROMPT_SESSION));
+    OptionalExtendedPolicyResult opt = AceDAO::getPolicyResult(attributeSet);
+
+    PolicyResult effect(PolicyEffect::DENY);
+    if (!opt.IsNull()) {
+        effect = opt->policyResult;
+    }
+
+    RUNNER_ASSERT(effect == PolicyEffect::PROMPT_SESSION);
+}
+
+TESTSUITE06(05){
+    CLEANENV;
+    AttributeSet attributeSet;
+    std::string tmp("atrS");
+    std::string tmpValue("Buu");
+    BaseAttributePtr atr(new Attribute(&tmp,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+    attributeSet.insert(atr);
+
+    AceDAO::setPolicyResult(attributeSet,
+                            ExtendedPolicyResult(PolicyEffect::PROMPT_BLANKET));
+    OptionalExtendedPolicyResult opt = AceDAO::getPolicyResult(attributeSet);
+
+    PolicyResult effect(PolicyEffect::DENY);
+    if (!opt.IsNull()) {
+        effect = opt->policyResult;
+    }
+
+    RUNNER_ASSERT(effect == PolicyEffect::PROMPT_BLANKET);
+}
+
+TESTSUITE06(06){
+    CLEANENV;
+    AttributeSet attributeSet;
+    std::string tmp("atrS");
+    std::string tmpValue("Buu");
+    BaseAttributePtr atr(new Attribute(&tmp,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+    attributeSet.insert(atr);
+
+    AceDAO::setPolicyResult(attributeSet,
+                            ExtendedPolicyResult(PolicyDecision::NOT_APPLICABLE));
+    OptionalExtendedPolicyResult opt = AceDAO::getPolicyResult(attributeSet);
+
+    PolicyResult effect(PolicyEffect::DENY);
+    if (!opt.IsNull()) {
+        effect = opt->policyResult;
+    }
+
+    RUNNER_ASSERT(effect == PolicyDecision::NOT_APPLICABLE);
+}
+
+TESTSUITE06(07){
+    CLEANENV;
+    AttributeSet attributeSet;
+    std::string tmp("atrS");
+    std::string tmpValue("Buu");
+    BaseAttributePtr atr(new Attribute(&tmp,
+                                       Attribute::Match::Equal,
+                                       Attribute::Type::Subject));
+    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+    attributeSet.insert(atr);
+
+    AceDAO::setPolicyResult(attributeSet,
+                            ExtendedPolicyResult(PolicyResult::UNDETERMINED));
+    OptionalExtendedPolicyResult opt = AceDAO::getPolicyResult(attributeSet);
+
+    PolicyResult effect(PolicyEffect::DENY);
+    if (!opt.IsNull()) {
+        effect = opt->policyResult;
+    }
+
+    RUNNER_ASSERT(effect == PolicyResult::UNDETERMINED);
+}
+
+TESTSUITE06(08){
+    CLEANENV;
+    int ruleId = 4;
+    std::string tmp("atrS2");
+    std::string tmpValue("Buu2");
+    std::string session = "jlakjhqrwebn234324987";
+
+    AceDAO::setPromptDecision(TEST_WIDGET_HANDLE,
+                              ruleId,
+                              DPL::FromUTF8String(session),
+                              PromptDecision::ALLOW_ALWAYS);
+
+    OptionalCachedPromptDecision decision =
+        AceDAO::getPromptDecision(TEST_WIDGET_HANDLE,
+                                  ruleId);
+
+    DPL::String session1;
+    PromptDecision dec = PromptDecision::DENY_FOR_SESSION;
+    if (!decision.IsNull()){
+        dec = (*decision).decision;
+        if (!decision.IsNull()) {
+            session1 = *((*decision).session);
+        }
+    }
+    RUNNER_ASSERT(dec == PromptDecision::ALLOW_ALWAYS);
+    RUNNER_ASSERT(DPL::ToUTF8String(session1) == session);
+}
+
+TESTSUITE06(09){
+    CLEANENV;
+    int ruleId = 5;
+    std::string tmp("atrS2");
+    std::string tmpValue("Buu2");
+
+    AceDAO::setPromptDecision(TEST_WIDGET_HANDLE,
+                                  ruleId,
+                                  DPL::OptionalString(),
+                                  PromptDecision::ALLOW_FOR_SESSION);
+
+    OptionalCachedPromptDecision decision =
+        AceDAO::getPromptDecision(TEST_WIDGET_HANDLE, ruleId);
+
+    PromptDecision dec = PromptDecision::DENY_FOR_SESSION;
+    if (!decision.IsNull()){
+        dec = (*decision).decision;
+        RUNNER_ASSERT((*decision).session.IsNull());
+    }
+    RUNNER_ASSERT(dec == PromptDecision::ALLOW_FOR_SESSION);
+}
+
+///*findVerdict*/
+//
+//void AceDAOTester::test3()
+//{
+//// Tests does verdict is stored for validity always
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS3");
+//    std::string tmpValue("Buu3");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_PERMIT;
+//    Validity val = Validity::ALWAYS;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_PERMIT);
+//    handleResult(result, "find Verdict test 3");
+//}
+///*findVerdict*/
+//
+//void AceDAOTester::test4()
+//{
+////tests does verdict is propertly stored (NOT saved)when session is Validity::ONCE
+////and verdict is DENY
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS4");
+//    std::string tmpValue("Buu4");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_DENY;
+//    Validity val = Validity::ONCE;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict test 4");
+//}
+///*findVerdict*/
+//
+//void AceDAOTester::test5()
+//{
+////tests does verdict is properly set when validity is session
+////and verdict is deny
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS5");
+//    std::string tmpValue("Buu5");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_DENY;
+//    Validity val = Validity::SESSION;
+//    pip.setSessionId("5");
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    pip.setSessionId("5");
+//    session = getSession();
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_DENY);
+//    handleResult(result, "find Verdict test 5");
+//}
+///*findVerdict*/
+//
+//void AceDAOTester::test6()
+//{
+////tests does verdict is properly stored for DENY Validity::ALWAYS
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS6");
+//    std::string tmpValue("Buu6");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_DENY;
+//    Validity val = Validity::ALWAYS;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_DENY);
+//    handleResult(result, "find Verdict test 6");
+//}
+//
+//
+//void AceDAOTester::test7()
+//{
+////tests stored version fo INAPPLICABLE Validity::ONCE
+//
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    attributeSet.insert(constructAttribute("atrS7","Buu7"));
+//    Verdict ver = Verdict::VERDICT_INAPPLICABLE;
+//    Validity val = Validity::ONCE;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    //Verdict with 'Once' validity should not be stored, therefore
+//    //the outcome should be UNKNOWN
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict test 7");
+//}
+//
+//
+//void AceDAOTester::test8()
+//{
+////tests storing data for verdict INAPLICABLE and Validity::SESSION
+//
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    attributeSet.insert(constructAttribute("atrS8","Buuu8"));
+//    Verdict ver = Verdict::VERDICT_INAPPLICABLE;
+//    Validity val = Validity::SESSION;
+//    pip.setSessionId("8");
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    pip.setSessionId("9");
+//    session = getSession();
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict test 8");
+//}
+///*findVerdict*/
+//
+//void AceDAOTester::test9()
+//{
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS9");
+//    std::string tmpValue("Buu9");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_INAPPLICABLE;
+//    Validity val = Validity::ALWAYS;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_INAPPLICABLE);
+//    handleResult(result, "find Verdict test 9");
+//}
+///*findVerdict*/
+//
+//void AceDAOTester::test10()
+//{
+////tests does verdict is properly stored for verdict undetermined
+////and validity Validity::ONCE - thats why verdict is UNKNOWN
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS10");
+//    std::string tmpValue("Buu10");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_UNDETERMINED;
+//    Validity val = Validity::ONCE;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict test 10");
+//}
+///*findVerdict*/
+//
+//void AceDAOTester::test11()
+//{
+////tests does verdict is properly stored for verdict undetermined
+////and validity Validity::SESSION - TODO Verdicts for undetermined are not stored??
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS11");
+//    std::string tmpValue("Buu11");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_UNDETERMINED;
+//    pip.setSessionId("8");
+//    Validity val = Validity::SESSION;
+//    pip.setSessionId("8");
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict test 11");
+//}
+///*findVerdict*/
+//
+//void AceDAOTester::test12()
+//{
+////tests does verdict is properly stored for verdict undetermined
+////and validity Validity::ALWAYS - TODO Verdicts for undetermined are not stored??
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS12");
+//    std::string tmpValue("Buu12");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_UNDETERMINED;
+//    Validity val = Validity::ALWAYS;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict test 12");
+//}
+///*findVerdict*/
+//
+//void AceDAOTester::test13()
+//{
+////tests does verdict is properly stored for verdict unknown
+////and validity Validity::ONCE-thats why  verdict is not stored
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS13");
+//    std::string tmpValue("Buu13");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_UNKNOWN;
+//    Validity val = Validity::ONCE;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict test 13");
+//}
+///*findVerdict*/
+//
+//void AceDAOTester::test14()
+//{
+////tests does verdict is properly stored for verdict unknown
+////and validity session- TODO why is the verdict not stored?
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS14");
+//    std::string tmpValue("Buu14");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_UNKNOWN;
+//    Validity val = Validity::SESSION;
+//    pip.setSessionId("8");
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    pip.setSessionId("8");
+//    session = getSession();
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict test 14");
+//}
+///*findVerdict*/
+//
+//void AceDAOTester::test15()
+//{
+////tests does verdict is properly stored for verdict unknown and
+////validity Validity::ALWAYS - TODO should we save Unknown verdict?
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS15");
+//    std::string tmpValue("Buu15");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_UNKNOWN;
+//    Validity val = Validity::ALWAYS;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict test 15");
+//}
+//
+///*removeVerdict*/         //tests does verdict is properly removed
+//void AceDAOTester::test16()
+//{
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS15");
+//    std::string tmpValue("Buu15");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//
+//    Verdict ver = Verdict::VERDICT_PERMIT;
+//    Validity val = Validity::ALWAYS;
+//    //add verdict
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    //check has verdict been stored?
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_PERMIT);
+//    handleResult(result, "find Verdict test 16: partA");
+//
+//    //remove verdict
+//    VerdictLogic::removeVerdict(request, attributeSet);
+//    //verified removed
+//    verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    result = VSPAssertEqual(verdict, Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict test 16: partB");
+//}
+//
+///*findVerdict*/
+//void AceDAOTester::test18()
+//{
+////verdict for 3 elements on the set of attributes
+//    Request  request("subject18","resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS60");
+//    std::string tmpValue("Buu60");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//
+//    std::string tmp1("atrS61");
+//    std::string tmpValue1("Buu61");
+//    BaseAttributePtr atr1(
+//        new Attribute(&tmp1,Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr1)->addValue(&tmpValue1);
+//    attributeSet.insert(atr1);
+//
+//    std::string tmp2("atrS62");
+//    std::string tmpValue2("Buu62");
+//    BaseAttributePtr atr2(
+//        new Attribute(&tmp2,Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr2)->addValue(&tmpValue2);
+//    attributeSet.insert(atr2);
+//
+//    Verdict ver = Verdict::VERDICT_DENY;
+//    Validity val = Validity::ALWAYS;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_DENY);
+//    handleResult(result, "find Verdict test 18");
+//}
+//
+///*resetDatabase*/
+//void AceDAOTester::test19()
+//{
+//    //tests reset DB
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS15");
+//    std::string tmpValue("Buu15");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//
+//    Verdict ver = Verdict::VERDICT_PERMIT;
+//    Validity val = Validity::ALWAYS;
+//    //add verdict
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    //check has verdict been stored?
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict, Verdict::VERDICT_PERMIT);
+//    handleResult(result, "reset database test 19: partA");
+//
+//    AceDAO::resetDatabase();
+//
+//    verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    result = VSPAssertEqual(verdict, Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "reset database test 19: partB");
+//}
+
+
+/*setWidgetDevCapSetting*/
+
+TESTSUITE06(26){
+    CLEANENV;
+    std::string res("res20");
+    WidgetHandle sub = 20;
+
+    SettingsLogic::setWidgetDevCapSetting(res, sub, Preference::PREFERENCE_PERMIT);
+    std::list<PermissionTriple> userSettings;
+    SettingsLogic::getWidgetDevCapSettings(&userSettings);
+    RUNNER_ASSERT(
+        UserSettingEqual(
+            &userSettings, res, sub, Preference::PREFERENCE_PERMIT));
+}
+
+/*setWidgetDevCapSetting*/
+
+TESTSUITE06(27){
+    CLEANENV;
+    std::string res("res21");
+    WidgetHandle sub = 21;
+
+    SettingsLogic::setWidgetDevCapSetting(res, sub, Preference::PREFERENCE_DENY);
+    std::list<PermissionTriple> userSettings;
+    SettingsLogic::getWidgetDevCapSettings(&userSettings);
+    RUNNER_ASSERT(
+        UserSettingEqual(
+            &userSettings, res, sub, Preference::PREFERENCE_DENY));
+}
+
+/*setWidgetDevCapSetting*/
+
+TESTSUITE06(28){
+    CLEANENV;
+    std::string res("res22");
+    WidgetHandle sub = 22;
+    AceDAO::clearAllSettings();
+    SettingsLogic::setWidgetDevCapSetting(res, sub, Preference::PREFERENCE_DEFAULT);
+    std::list<PermissionTriple> userSettings;
+    SettingsLogic::getWidgetDevCapSettings(&userSettings);
+    RUNNER_ASSERT(
+        UserSettingEqual(
+            &userSettings, res, sub, Preference::PREFERENCE_DEFAULT));
+}
+
+TESTSUITE06(29){
+    CLEANENV;
+    std::string res("res23");
+    WidgetHandle sub = 23;
+
+    SettingsLogic::setWidgetDevCapSetting(res, sub, Preference::PREFERENCE_DEFAULT);
+    SettingsLogic::setWidgetDevCapSetting(res, sub, Preference::PREFERENCE_DENY);
+    std::list<PermissionTriple> userSettings;
+    SettingsLogic::getWidgetDevCapSettings(&userSettings);
+    RUNNER_ASSERT(
+        UserSettingEqual(
+            &userSettings, res, sub, Preference::PREFERENCE_DENY));
+}
+
+/*setWidgetDevCapSettings*/
+
+TESTSUITE06(30){
+    CLEANENV;
+    std::string resa("res24a");
+    WidgetHandle suba = 241;
+    std::string resb("res24b");
+    WidgetHandle subb = 242;
+
+    std::list<PermissionTriple> permissionsL;
+
+    permissionsL.push_back(
+        PermissionTriple(suba, resa, Preference::PREFERENCE_DENY));
+    permissionsL.push_back(
+        PermissionTriple(subb, resb, Preference::PREFERENCE_PERMIT));
+
+    SettingsLogic::setWidgetDevCapSettings(permissionsL);
+
+    std::list<PermissionTriple> userSettings;
+    SettingsLogic::getWidgetDevCapSettings(&userSettings);
+    RUNNER_ASSERT(
+        UserSettingsAgreed(&permissionsL, &userSettings));
+}
+
+
+
+TESTSUITE06(31){
+    CLEANENV;
+//multi set - if value is not set in DB or has DEFAUL value it is not
+//send by getWidgetDevCapSettings - optimization
+
+    std::string resa("res25a");
+    WidgetHandle suba = 251;
+    std::string resb("res25b");
+    WidgetHandle subb = 252;
+    std::string resc("res25c");
+    WidgetHandle subc = 253;
+
+    std::list<PermissionTriple> permissionsL;
+
+    permissionsL.push_back(
+        PermissionTriple(suba, resa, Preference::PREFERENCE_DENY));
+    permissionsL.push_back(
+        PermissionTriple(subb, resb, Preference::PREFERENCE_PERMIT));
+    permissionsL.push_back(
+        PermissionTriple(subc, resc, Preference::PREFERENCE_DEFAULT));
+
+
+    SettingsLogic::setWidgetDevCapSettings(permissionsL);
+
+    std::list<PermissionTriple> userSettings;
+    SettingsLogic::getWidgetDevCapSettings(&userSettings);
+    RUNNER_ASSERT(UserSettingsAgreed(&permissionsL, &userSettings));
+}
+
+TESTSUITE06(32){
+    CLEANENV;
+    //empty list  -- TODO what is it testing?
+    std::list<PermissionTriple> permissionsL;
+
+    std::list<PermissionTriple> userSettings;
+    SettingsLogic::getWidgetDevCapSettings(&userSettings);
+    RUNNER_ASSERT(UserSettingsAgreed(&permissionsL, &userSettings));
+}
+
+TESTSUITE06(33){
+    CLEANENV;
+    //test resource setting PERMIT
+    std::string res("res27");
+    SettingsLogic::setDevCapSetting(res, Preference::PREFERENCE_PERMIT);
+    std::map<std::string, Preference> resourceSettings;
+    SettingsLogic::getDevCapSettings(&resourceSettings);
+
+    RUNNER_ASSERT(
+         ResourceSettingEqual(&resourceSettings,
+                              res,
+                              Preference::PREFERENCE_PERMIT));
+}
+
+TESTSUITE06(34){
+    CLEANENV;
+    //test resource setting DENY
+    std::string res("res28");
+    SettingsLogic::setDevCapSetting(res, Preference::PREFERENCE_DENY);
+    std::map<std::string, Preference> resourceSettings;
+    SettingsLogic::getDevCapSettings(&resourceSettings);
+
+    RUNNER_ASSERT(
+        ResourceSettingEqual(&resourceSettings,
+                             res,
+                             Preference::PREFERENCE_DENY));
+}
+
+TESTSUITE06(35){
+    CLEANENV;
+    //test resource setting Preference::PREFERENCE_DEFAULT
+
+    std::string res("res29");
+    SettingsLogic::setDevCapSetting(res, Preference::PREFERENCE_DEFAULT);
+    std::map<std::string, Preference> resourceSettings;
+    SettingsLogic::getDevCapSettings(&resourceSettings);
+
+    RUNNER_ASSERT(
+        ResourceSettingEqual(
+            &resourceSettings,
+            res,
+            Preference::PREFERENCE_DEFAULT));
+}
+
+TESTSUITE06(36){
+    CLEANENV;
+    //multi set for Resource settings
+
+    std::string resa("res30a");
+    std::string resb("res30b");
+
+    std::list<std::pair<const std::string*, Preference> > resourcesL;
+    resourcesL.push_back(make_pair(&resa, Preference::PREFERENCE_DENY));
+    resourcesL.push_back(make_pair(&resb, Preference::PREFERENCE_PERMIT));
+
+    SettingsLogic::setAllDevCapSettings (resourcesL);
+
+    std::map<std::string, Preference> resourceSettings;
+    SettingsLogic::getDevCapSettings(&resourceSettings);
+    RUNNER_ASSERT(ResourceSettingsAgreed(&resourcesL, &resourceSettings));
+
+}
+
+//void AceDAOTester::test31()
+//{
+//    // session has changed (PERMIT).
+//    //What is the verdict now?
+//
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS31");
+//    std::string tmpValue("Buu31");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_PERMIT;
+//    Validity val = Validity::SESSION;
+//    pip.setSessionId("aaa");
+//
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdictA =
+//        VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultA = VSPAssertEqual(verdictA, Verdict::VERDICT_PERMIT);
+//    handleResult(resultA, "Verdict session test 31 session a");
+//
+//    pip.setSessionId("bbb");
+//    session = getSession();
+//    Verdict verdictB =
+//        VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultB = VSPAssertEqual(verdictB, Verdict::VERDICT_UNKNOWN);
+//    handleResult(resultB, "Verdict session test 31 session b");
+//}
+
+
+//void AceDAOTester::test32()
+//{
+//    //session has changed (DENY).
+//    //what is the verdict?
+//
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS32");
+//    std::string tmpValue("Buu32");
+//    BaseAttributePtr atr(
+//        new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver = Verdict::VERDICT_DENY;
+//    Validity val = Validity::SESSION;
+//    pip.setSessionId("aaa");
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdictA =
+//        VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultA = VSPAssertEqual(verdictA, Verdict::VERDICT_DENY);
+//    handleResult(resultA, "Verdict session test 32 session a");
+//
+//    pip.setSessionId("ccc");
+//
+//    session = getSession();
+//    Verdict verdictB =
+//        VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultB = VSPAssertEqual(verdictB, Verdict::VERDICT_UNKNOWN);
+//    handleResult(resultB, "Verdict session test 32 session b");
+//}
+
+//void AceDAOTester::test33(){
+//
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS33");
+//    std::string tmpValue("Buu33");
+//    BaseAttributePtr atr(new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver =  Verdict::VERDICT_INAPPLICABLE;
+//    Validity val = Validity::SESSION;
+//    pip.setSessionId("aaa");
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdictA = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultA = VSPAssertEqual(verdictA, Verdict::VERDICT_INAPPLICABLE);
+//    handleResult(resultA, "Verdict session test 33 session a");
+//
+//    pip.setSessionId("bbb");
+//
+//    session = getSession();
+//    Verdict verdictB = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultB = VSPAssertEqual(verdictB, Verdict::VERDICT_UNKNOWN);
+//    handleResult(resultB, "Verdict session test 33 session b");
+//}
+
+//void AceDAOTester::test34(){ //session has changed (UNDETERMINED).
+////what is the verdict?
+//
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS34");
+//    std::string tmpValue("Buu34");
+//    BaseAttributePtr atr(new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver =  Verdict::VERDICT_UNDETERMINED;
+//    Validity val = Validity::SESSION;
+//    pip.setSessionId("aaa");
+//    std::string session  = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdictA = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultA = VSPAssertEqual(verdictA, Verdict::VERDICT_UNKNOWN);
+//    handleResult(resultA, "Verdict session test 34 session a");
+//
+//    pip.setSessionId("bbb");
+//
+//    session = getSession();
+//    Verdict verdictB = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultB = VSPAssertEqual(verdictB, Verdict::VERDICT_UNKNOWN);
+//    handleResult(resultB, "Verdict session test 34 session b");
+//}
+
+//void AceDAOTester::test35(){  //session has changed(UNKNOWN),
+////what is the verdict?
+//
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS35");
+//    std::string tmpValue("Buu35");
+//    BaseAttributePtr atr(new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver =  Verdict::VERDICT_UNKNOWN;
+//    Validity val = Validity::SESSION;
+//    pip.setSessionId("aaa");
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdictA = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultA = VSPAssertEqual(verdictA, Verdict::VERDICT_UNKNOWN);
+//    handleResult(resultA, "Verdict session test 35 session a");
+//    pip.setSessionId("bbb");
+//
+//    session = getSession();
+//    Verdict verdictB = VerdictLogic::findVerdict(request, session,attributeSet);
+//    bool resultB = VSPAssertEqual(verdictB, Verdict::VERDICT_UNKNOWN);
+//    handleResult(resultB, "Verdict session test 35 session b");
+//}
+
+//void AceDAOTester::test36(){ //changed verdict in the same session
+//
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS36");
+//    std::string tmpValue("Buu36");
+//    BaseAttributePtr atr(new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//    Verdict ver =  Verdict::VERDICT_DENY;
+//    Validity val = Validity::SESSION;
+//    pip.setSessionId("aaa");
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdictA = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultA = VSPAssertEqual(verdictA ,Verdict::VERDICT_DENY);
+//    handleResult(resultA, "Verdict session test 36 session a");
+//
+//    ver =  Verdict::VERDICT_PERMIT;
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdictB = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultB = VSPAssertEqual(verdictB ,Verdict::VERDICT_PERMIT);
+//    handleResult(resultB, "Verdict session test 36 session b");
+//}
+//
+///* User settings crash tests */
+//
+//
+//void AceDAOTester::test37(){ //empty attribute and verdict permit always
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//
+//    Verdict ver = Verdict::VERDICT_PERMIT;
+//    Validity val = Validity::ALWAYS;
+//
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict,Verdict::VERDICT_PERMIT);
+//    handleResult(result, "find Verdict empty attribute set test 37 ");
+//}
+//
+//void AceDAOTester::test38(){ //empty attribute and verdict deny always
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//
+//    Verdict ver = Verdict::VERDICT_DENY;
+//    Validity val = Validity::ALWAYS;
+//
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict,Verdict::VERDICT_DENY);
+//    handleResult(result, "find Verdict empty attribute set test 38 ");
+//}
+//
+//void AceDAOTester::test39(){
+//
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//
+//    Verdict ver = Verdict::VERDICT_INAPPLICABLE;
+//    Validity val = Validity::ALWAYS;
+//
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict,Verdict::VERDICT_INAPPLICABLE);
+//    handleResult(result, "find Verdict empty attribute set test 39 ");
+//}
+//
+//void AceDAOTester::test40(){ //empty attribute and verdict unknown
+//    Request  request("subject", "resource");
+//    AttributeSet attributeSet;
+//
+//    Verdict ver = Verdict::VERDICT_UNKNOWN;
+//    Validity val = Validity::ALWAYS;
+//
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict,Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict empty attribute set test 40 ");
+//}
+//
+//void AceDAOTester::test41()
+//{
+//    //empty string as subject and resource,
+//    //without attributes and verdit DENY Validity::ALWAYS
+//    Request  request("", "");
+//    //TODO is it OK to store Verdict::VERDICT for empty request?
+//    AttributeSet attributeSet;
+//
+//    Verdict ver = Verdict::VERDICT_DENY;
+//    Validity val = Validity::ALWAYS;
+//
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict,Verdict::VERDICT_DENY);
+//    //bool result = VSPAssertEqual(verdict,Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict empty request empty "
+//                         "attribute set test 41 ");
+//}
+//
+//void AceDAOTester::test42(){
+//    //empty string as subject and resource, without attributes
+//    //and verdict is PERMIT Validity::ALWAYS
+//    Request  request("", "");
+//
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS42");
+//    std::string tmpValue("Buu342");
+//    BaseAttributePtr atr(new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//
+//    Verdict ver = Verdict::VERDICT_PERMIT;
+//    Validity val = Validity::ALWAYS;
+//
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict,Verdict::VERDICT_PERMIT);
+//    handleResult(result, "find Verdict empty request test 42 ");
+//}
+//
+//void AceDAOTester::test43(){
+//    //TODO I have changed it! verdict
+//    //has changed and stored in DB. does current verdict is the last one?
+//
+//    Request  request("ac", "ca");
+//    AttributeSet attributeSet;
+//
+//    Verdict ver = Verdict::VERDICT_DENY;
+//    Verdict verp = Verdict::VERDICT_PERMIT;
+//    Validity val = Validity::ALWAYS;
+//
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//    VerdictLogic::addVerdict(request, session, attributeSet, verp, val);
+//
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict,Verdict::VERDICT_PERMIT);
+//    handleResult(result, "find Verdict empty request empty "
+//                         "attribute set test 43 ");
+//}
+//
+//void AceDAOTester::test44(){
+//    //empty subject and resource name - get Atributes list
+//    Request  request("","");
+//
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS44");
+//    std::string tmpValue("Buu44");
+//    BaseAttributePtr atr(new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//
+//    Verdict ver = Verdict::VERDICT_PERMIT;
+//    Validity val = Validity::ALWAYS;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    AttributeSet attributeS;
+//    AceDAO::getAttributes(&attributeS);
+//
+//    bool result = false;
+//
+//    result = AttributeEqual(attributeSet,attributeS);
+//
+//    handleResult(!result,"find Attributes empty request  test 44");
+//}
+//
+//void AceDAOTester::test45(){
+//    //empty subject and resource name - what is the verdict? - is it OK??
+//    Request  request("", "");
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS15");
+//    std::string tmpValue("Buu15");
+//    BaseAttributePtr atr(new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//
+//    Verdict ver = Verdict::VERDICT_PERMIT;
+//    Validity val = Validity::ALWAYS;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(request, session, attributeSet, ver, val);
+//
+//    VerdictLogic::removeVerdict(request, attributeSet);
+//
+//    Verdict verdict = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool result = VSPAssertEqual(verdict,Verdict::VERDICT_UNKNOWN);
+//    handleResult(result, "find Verdict test 45");
+//}
+//
+//void AceDAOTester::test46(){
+//    // TODO is it ok that for empty subject and resource name
+//    // the verdict is not stored
+//    Request  requestemp("", "");
+//    Request  request("aa","bb");
+//
+//    AttributeSet attributeSet;
+//    std::string tmp("atrS46");
+//    std::string tmpValue("Buu146");
+//    BaseAttributePtr atr(new Attribute(&tmp, Attribute::Match::Equal, Attribute::Type::Subject));
+//    DPL::StaticPointerCast<Attribute>(atr)->addValue(&tmpValue);
+//    attributeSet.insert(atr);
+//
+//    Verdict verAdd = Verdict::VERDICT_PERMIT;
+//    Validity val = Validity::ALWAYS;
+//    std::string session = getSession();
+//    VerdictLogic::addVerdict(requestemp, session, attributeSet, verAdd, val);
+//    VerdictLogic::addVerdict(request, session, attributeSet, verAdd, val);
+//
+//    VerdictLogic::removeVerdict(requestemp, attributeSet);
+//
+//    Verdict verdictA = VerdictLogic::findVerdict(requestemp, session, attributeSet);
+//    bool resultA = VSPAssertEqual(verdictA,Verdict::VERDICT_UNKNOWN);
+//    handleResult(resultA,"find Verdict test 46 A ");
+//
+//    Verdict verdictB = VerdictLogic::findVerdict(request, session, attributeSet);
+//    bool resultB = VSPAssertEqual(verdictB, Verdict::VERDICT_PERMIT);
+//    handleResult(resultB,"find Verdict test 46 B ");
+//
+//}
+
+TESTSUITE06(53){
+    CLEANENV;
+    //Empty resource name
+    std::string res("");
+    SettingsLogic::setDevCapSetting(res, Preference::PREFERENCE_PERMIT);
+    std::map<std::string, Preference> resourceSettings;
+    SettingsLogic::getDevCapSettings(&resourceSettings);
+
+    RUNNER_ASSERT(
+        ResourceSettingEqual(
+            &resourceSettings,
+            res,
+            Preference::PREFERENCE_PERMIT));
+}
+
+//void AceDAOTester::test48(){
+//    SettingsLogic::setResourceSetting(NULL, PERMIT);
+//    std::map<std::string, Preference>*  resourceSettings =
+//        SettingsLogic::getResourceSettings();
+//
+//    bool result = ResourceSettingEqual(resourceSettings, NULL,PERMIT );
+//    handleResult(result, "get Resource Settings empty resource test 48");
+//    printf("get Resource Settings empty resource test 48 -----> "
+//           "Segmentation fault\n");
+//}
+
+TESTSUITE06(55){
+    CLEANENV;
+    //resource settings list with empty elemen
+
+    std::string resb("");
+
+    std::list<std::pair<const std::string*, Preference> > resourcesL;
+    resourcesL.push_back(make_pair(&resb, Preference::PREFERENCE_PERMIT));
+
+    SettingsLogic::setAllDevCapSettings (resourcesL);
+
+    std::map<std::string, Preference> resourceSettings;
+    SettingsLogic::getDevCapSettings(&resourceSettings);
+    RUNNER_ASSERT(ResourceSettingsEqual(&resourcesL, &resourceSettings));
+}
+
+TESTSUITE06(56){
+    CLEANENV;
+    //user settings with empty subject and resource
+    //if resource or subject name is empty, values are not saved in DB
+    std::string resb("fake-resource");
+    WidgetHandle subb = 0;
+
+    std::list<PermissionTriple> permissionsL;
+
+    permissionsL.push_back(PermissionTriple(subb, resb, Preference::PREFERENCE_PERMIT));
+
+    SettingsLogic::setWidgetDevCapSettings(permissionsL);
+
+    std::list<PermissionTriple> userSettings;
+    SettingsLogic::getWidgetDevCapSettings(&userSettings);
+    RUNNER_ASSERT(UserSettingsAgreed(&permissionsL, &userSettings));
+}
+
+TESTSUITE06(57){
+    CLEANENV;
+    //user setting equal
+    // settings with at least one empty value is not set
+    std::string res("");
+    WidgetHandle sub = 0;
+
+    SettingsLogic::setWidgetDevCapSetting(res, sub, Preference::PREFERENCE_PERMIT);
+    std::list<PermissionTriple> userSettings;
+    SettingsLogic::getWidgetDevCapSettings(&userSettings);
+    RUNNER_ASSERT(
+        UserSettingNotStored(
+            &userSettings,
+            res,
+            sub,
+            Preference::PREFERENCE_PERMIT));
+}
+
+TESTSUITE06(58){
+    CLEANENV;
+    //user settings empty values and Default access
+
+    std::string res("");
+    WidgetHandle sub = 0;
+
+    SettingsLogic::setWidgetDevCapSetting(res, sub, Preference::PREFERENCE_DEFAULT);
+    std::list<PermissionTriple> userSettings;
+    SettingsLogic::getWidgetDevCapSettings(&userSettings);
+    RUNNER_ASSERT(
+        UserSettingNotStored(
+            &userSettings,
+            res,
+            sub,
+            Preference::PREFERENCE_DEFAULT));
+}
+
+TESTSUITE06(59){
+    CLEANENV;
+    DPL::OptionalString sessionId(DPL::FromUTF8String("fakesession"));
+    AceDAO::setPromptDecision(59, 4, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+
+    OptionalCachedPromptDecision dec = AceDAO::getPromptDecision(59, 4);
+
+    RUNNER_ASSERT(!dec.IsNull());
+
+    if (!dec.IsNull())
+    {
+        RUNNER_ASSERT(dec->decision == PromptDecision::ALLOW_FOR_SESSION);
+        RUNNER_ASSERT(!(dec->session.IsNull()));
+        if (!(dec->session.IsNull())) {
+            RUNNER_ASSERT(*(dec->session) == *sessionId);
+        }
+    }
+}
+
+TESTSUITE06(60){
+    CLEANENV;
+    DPL::OptionalString sessionId(DPL::FromUTF8String("fakesession44"));
+    AceDAO::setPromptDecision(60, 4, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+    AceDAO::setPromptDecision(60, 4, sessionId, PromptDecision::DENY_FOR_SESSION);
+
+    OptionalCachedPromptDecision dec = AceDAO::getPromptDecision(60, 4);
+
+    RUNNER_ASSERT(!dec.IsNull());
+
+    if (!dec.IsNull())
+    {
+        RUNNER_ASSERT(dec->decision == PromptDecision::DENY_FOR_SESSION);
+        RUNNER_ASSERT(!(dec->session.IsNull()));
+        if (!(dec->session.IsNull())) {
+            RUNNER_ASSERT(*(dec->session) == *sessionId);
+        }
+    }
+}
+
+TESTSUITE06(61){
+    CLEANENV;
+    DPL::OptionalString sessionId(DPL::FromUTF8String("fakesessionxxx"));
+    AceDAO::setPromptDecision(61, 4, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+    AceDAO::setPromptDecision(61, 4, sessionId, PromptDecision::DENY_FOR_SESSION);
+    AceDAO::setPromptDecision(61, 5, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+    AceDAO::setPromptDecision(61, 3, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+    AceDAO::setPromptDecision(61, 5, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+    AceDAO::setPromptDecision(61, 3, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+
+    OptionalCachedPromptDecision dec = AceDAO::getPromptDecision(61, 4);
+
+    RUNNER_ASSERT(!dec.IsNull());
+
+    if (!dec.IsNull())
+    {
+        RUNNER_ASSERT(dec->decision == PromptDecision::DENY_FOR_SESSION);
+        RUNNER_ASSERT(!(dec->session.IsNull()));
+        if (!(dec->session.IsNull())) {
+            RUNNER_ASSERT(*(dec->session) == *sessionId);
+        }
+    }
+}
+
+TESTSUITE06(62){
+    CLEANENV;
+    DPL::OptionalString sessionId(DPL::FromUTF8String("fakesession63"));
+    AceDAO::setPromptDecision(61, 4, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+    AceDAO::setPromptDecision(61, 4, sessionId, PromptDecision::DENY_FOR_SESSION);
+    AceDAO::setPromptDecision(60, 4, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+    AceDAO::setPromptDecision(60, 4, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+    AceDAO::setPromptDecision(62, 4, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+    AceDAO::setPromptDecision(62, 4, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+
+    OptionalCachedPromptDecision dec = AceDAO::getPromptDecision(61, 4);
+
+    RUNNER_ASSERT(!dec.IsNull());
+
+    if (!dec.IsNull())
+    {
+        RUNNER_ASSERT(dec->decision == PromptDecision::DENY_FOR_SESSION);
+        RUNNER_ASSERT(!(dec->session.IsNull()));
+        if (!(dec->session.IsNull())) {
+            RUNNER_ASSERT(*(dec->session) == *sessionId);
+        }
+    }
+}
+
+TESTSUITE06(63){
+    CLEANENV;
+    DPL::OptionalString sessionId(DPL::FromUTF8String("fakesession64"));
+    AceDAO::setPromptDecision(61, 4, sessionId, PromptDecision::DENY_FOR_SESSION);
+    AceDAO::setPromptDecision(61, 4, sessionId, PromptDecision::ALLOW_FOR_SESSION);
+    AceDAO::setPromptDecision(60, 4, sessionId, PromptDecision::DENY_FOR_SESSION);
+    AceDAO::setPromptDecision(60, 4, sessionId, PromptDecision::DENY_FOR_SESSION);
+    AceDAO::setPromptDecision(62, 4, sessionId, PromptDecision::DENY_FOR_SESSION);
+    AceDAO::setPromptDecision(62, 4, sessionId, PromptDecision::DENY_FOR_SESSION);
+
+    OptionalCachedPromptDecision dec = AceDAO::getPromptDecision(61, 4);
+
+    RUNNER_ASSERT(!dec.IsNull());
+
+    if (!dec.IsNull())
+    {
+        RUNNER_ASSERT(dec->decision == PromptDecision::ALLOW_FOR_SESSION);
+        RUNNER_ASSERT(!(dec->session.IsNull()));
+        if (!(dec->session.IsNull())) {
+            RUNNER_ASSERT(*(dec->session) == *sessionId);
+        }
+    }
+}
+
+TESTSUITE06(64){
+    CLEANENV;
+    DPL::OptionalString sessionId;
+    AceDAO::setPromptDecision(64, 5, sessionId, PromptDecision::DENY_ALWAYS);
+    AceDAO::setPromptDecision(64, 5, sessionId, PromptDecision::ALLOW_ALWAYS);
+    AceDAO::setPromptDecision(64, 4, sessionId, PromptDecision::DENY_FOR_SESSION);
+    AceDAO::setPromptDecision(63, 5, sessionId, PromptDecision::DENY_FOR_SESSION);
+
+    OptionalCachedPromptDecision dec = AceDAO::getPromptDecision(64, 5);
+
+    RUNNER_ASSERT(!dec.IsNull());
+
+    if (!dec.IsNull())
+    {
+        RUNNER_ASSERT(dec->decision == PromptDecision::ALLOW_ALWAYS);
+        RUNNER_ASSERT(dec->session.IsNull());
+    }
+}
+
+TESTSUITE06(65){
+    CLEANENV;
+    DPL::String f1(DPL::FromASCIIString("Feature1"));
+    DPL::String f2(DPL::FromASCIIString("Feature2"));
+    AceDB::FeatureNameVector fvector;
+    fvector.push_back(f1);
+    fvector.push_back(f2);
+    AceDAO::setAcceptedFeature(65, fvector);
+
+    fvector.clear();
+    AceDAO::getAcceptedFeature(65, &fvector);
+
+    RUNNER_ASSERT(fvector.size() == 2);
+    RUNNER_ASSERT(fvector[0] != fvector[1]);
+    RUNNER_ASSERT(fvector[0] == f1 || fvector[0] == f2);
+    RUNNER_ASSERT(fvector[1] == f1 || fvector[1] == f2);
+}
+
+TESTSUITE06(66){
+    CLEANENV;
+    AceDB::FeatureNameVector fvector;
+    fvector.push_back(DPL::FromASCIIString("Feature1"));
+    fvector.push_back(DPL::FromASCIIString("Feature2"));
+    AceDAO::setAcceptedFeature(66, fvector);
+
+    fvector.clear();
+    AceDAO::getAcceptedFeature(67, &fvector);
+
+    RUNNER_ASSERT(fvector.size() == 0);
+}
diff --git a/tests/ace/ace_tests.cpp b/tests/ace/ace_tests.cpp
new file mode 100644 (file)
index 0000000..675b6d5
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        main.cpp
+ * @author      Bartlomiej Grzelewski <b.grzelewski@samsung.com>
+ * @version     1.0
+ * @brief       This file is the implementation file of main
+ */
+#include <string>
+
+#include <dpl/test/test_runner.h>
+#include <dpl/log/log.h>
+
+#include <loop_control.h>
+
+#include <ace-dao-rw/AceDAO.h>
+
+#include "Interfaces.h"
+#include "PEPSingleton.h"
+
+using namespace LoopControl;
+
+class UnitTestThread
+{
+public:
+    UnitTestThread()
+    {
+        // Attach databases
+        AceDB::AceDAO::attachToThreadRW();
+    }
+
+    ~UnitTestThread()
+    {
+        // Detach databases
+        AceDB::AceDAO::detachFromThread();
+    }
+};
+
+int main (int argc, char *argv[])
+{
+    init_loop(argc, argv);
+
+    LogInfo("Initializing PEPSingleton.");
+
+    UnitTestThread attacher;
+
+    PEPSingleton::Instance().initialize(
+        new WebRuntimeImp(),
+        new ResourceInformationImp(),
+        new OperationSystemImp());
+
+    LogInfo("Starting tests.");
+
+    int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
+
+    PEPSingleton::Instance().terminate();
+
+    quit_loop();
+    return status;
+}
+
diff --git a/tests/ace/loop_control.cpp b/tests/ace/loop_control.cpp
new file mode 100644 (file)
index 0000000..15ede0d
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        loop_control.cpp
+ * @author      Jaroslaw Osmanski (j.osmanski@samsung.com)
+ * @version     1.0
+ * @brief       This is implementation of EFL version of loop control
+ */
+
+#include <dpl/log/log.h>
+
+#include <dpl/framework_efl.h>
+
+#include <glib.h>
+#include <glib-object.h>
+
+#include <loop_control.h>
+
+namespace LoopControl
+{
+void init_loop(int argc, char *argv[])
+{
+    (void)argc;
+    (void)argv;
+    g_type_init();
+//    g_thread_init(NULL);
+
+    LogInfo("Starting");
+    elm_init(argc, argv);
+}
+
+void wait_for_wrt_init()
+{
+    ecore_main_loop_begin();
+}
+
+void finish_wait_for_wrt_init()
+{
+    ecore_main_loop_quit();
+}
+
+void quit_loop()
+{
+    elm_shutdown();
+}
+
+void wrt_start_loop()
+{
+    ecore_main_loop_begin();
+}
+
+void wrt_end_loop()
+{
+    ecore_main_loop_quit();
+}
+
+void *abstract_window()
+{
+    return elm_win_add(NULL, "hello", ELM_WIN_BASIC);
+}
+
+}//end of LoopControl namespace
diff --git a/tests/ace/loop_control.h b/tests/ace/loop_control.h
new file mode 100644 (file)
index 0000000..30aa6e8
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        loop_control.cpp
+ * @author      Jaroslaw Osmanski (j.osmanski@samsung.com)
+ * @version     1.0
+ * @brief       This file is the definitions of loop controlling utilities
+ */
+
+
+#ifndef LOOP_CONTROL_H_
+#define LOOP_CONTROL_H_
+
+namespace LoopControl
+{
+
+void init_loop(int argc, char *argv[]);
+void wait_for_wrt_init();
+void finish_wait_for_wrt_init();
+void quit_loop();
+
+void wrt_start_loop();
+void wrt_end_loop();
+
+void *abstract_window();
+
+}
+
+#endif /* LOOP_CONTROL_H_ */
diff --git a/tests/ace/test-configuration/CMTest/CMakeLists.txt b/tests/ace/test-configuration/CMTest/CMakeLists.txt
new file mode 100644 (file)
index 0000000..d186839
--- /dev/null
@@ -0,0 +1,26 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/CMTest/pms_config.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/CMTest/pms_general-test.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/CMTest/policyTest1.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/CMTest/policyTest2.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/CMTest/policyTest3.xml
+    DESTINATION /usr/etc/ace/CMTest
+    PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ GROUP_WRITE
+  )
+
+ADD_SUBDIRECTORY(active)
+
diff --git a/tests/ace/test-configuration/CMTest/active/CMakeLists.txt b/tests/ace/test-configuration/CMTest/active/CMakeLists.txt
new file mode 100644 (file)
index 0000000..baefacf
--- /dev/null
@@ -0,0 +1,21 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/CMTest/active/pms_general-test.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/CMTest/active/bondixml.dtd
+    DESTINATION /usr/etc/ace/CMTest/active
+    PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ GROUP_WRITE
+  )
+
diff --git a/tests/ace/test-configuration/CMTest/active/bondixml.dtd b/tests/ace/test-configuration/CMTest/active/bondixml.dtd
new file mode 100644 (file)
index 0000000..42a6c7b
--- /dev/null
@@ -0,0 +1,199 @@
+<!ENTITY % Object.ANY ''>
+<!ENTITY % Method.ANY ''>
+<!ENTITY % Transform.ANY ''>
+<!ENTITY % SignatureProperty.ANY ''>
+<!ENTITY % KeyInfo.ANY ''>
+<!ENTITY % KeyValue.ANY ''> <!-- TODO ECDSA IS NOT HANDLED YET -->
+<!ENTITY % PGPData.ANY ''>
+<!ENTITY % X509Data.ANY ''>
+<!ENTITY % SPKIData.ANY ''>
+
+
+<!ELEMENT signed-policy (Signature, ( policy-set | policy )* ) >
+<!-- Start Core Signature declarations, these should NOT be altered -->
+
+<!ELEMENT Signature (SignedInfo, SignatureValue, KeyInfo?, Object*)  >
+<!ATTLIST Signature  
+       xmlns   CDATA   #FIXED 'http://www.w3.org/2000/09/xmldsig#'
+       Id      ID      #IMPLIED >
+
+<!ELEMENT SignatureValue (#PCDATA) >
+<!ATTLIST SignatureValue  
+         Id  ID      #IMPLIED>
+
+<!ELEMENT SignedInfo (CanonicalizationMethod, 
+       SignatureMethod,  Reference+)  >
+<!ATTLIST SignedInfo  
+       Id       ID      #IMPLIED 
+>
+
+<!ELEMENT CanonicalizationMethod (#PCDATA %Method.ANY;)* > 
+<!ATTLIST CanonicalizationMethod 
+       Algorithm CDATA #REQUIRED > 
+
+<!ELEMENT SignatureMethod (#PCDATA|HMACOutputLength %Method.ANY;)* >
+<!ATTLIST SignatureMethod 
+       Algorithm CDATA #REQUIRED > 
+
+<!ELEMENT Reference (DigestMethod, DigestValue)  >
+<!ATTLIST Reference
+       Id      ID      #IMPLIED
+       URI     CDATA   #IMPLIED
+       Type    CDATA   #IMPLIED>
+
+
+<!ELEMENT XPath (#PCDATA) >
+
+<!ELEMENT DigestMethod (#PCDATA %Method.ANY;)* >
+<!ATTLIST DigestMethod  
+       Algorithm               CDATA   #REQUIRED >
+
+<!ELEMENT DigestValue  (#PCDATA)  >
+
+<!ELEMENT KeyInfo      (#PCDATA|KeyName|KeyValue|RetrievalMethod|
+           X509Data|PGPData|SPKIData|MgmtData %KeyInfo.ANY;)* >
+<!ATTLIST KeyInfo
+       Id      ID       #IMPLIED >
+
+<!-- Key Information -->
+
+<!ELEMENT KeyName (#PCDATA) >
+<!ELEMENT KeyValue (#PCDATA|DSAKeyValue|RSAKeyValue %KeyValue.ANY;)* >
+<!ELEMENT MgmtData (#PCDATA) >
+
+<!ELEMENT RetrievalMethod EMPTY>
+<!ATTLIST RetrievalMethod
+  URI  CDATA #REQUIRED 
+  Type CDATA #IMPLIED > 
+
+<!-- X.509 Data -->
+
+<!ELEMENT X509Data ((X509IssuerSerial | X509SKI | X509SubjectName |
+                    X509Certificate | X509CRL )+ %X509Data.ANY;)>
+<!ELEMENT X509IssuerSerial (X509IssuerName, X509SerialNumber) >
+<!ELEMENT X509IssuerName (#PCDATA) >
+<!ELEMENT X509SubjectName (#PCDATA) >
+<!ELEMENT X509SerialNumber (#PCDATA) >
+<!ELEMENT X509SKI (#PCDATA) >
+<!ELEMENT X509Certificate (#PCDATA) >
+<!ELEMENT X509CRL (#PCDATA) >
+
+<!-- PGPData -->
+
+<!ELEMENT PGPData ((PGPKeyID, PGPKeyPacket?) | (PGPKeyPacket) %PGPData.ANY;) >
+<!ELEMENT PGPKeyPacket  (#PCDATA)  >
+<!ELEMENT PGPKeyID  (#PCDATA)  >
+
+<!-- SPKI Data -->
+
+<!ELEMENT SPKIData (SPKISexp %SPKIData.ANY;)  >
+<!ELEMENT SPKISexp  (#PCDATA)  >
+
+<!-- Extensible Content -->
+
+<!ELEMENT Object (#PCDATA|Signature|SignatureProperties|Manifest %Object.ANY;)* >
+<!ATTLIST Object  
+       Id      ID      #IMPLIED
+       MimeType        CDATA   #IMPLIED
+       Encoding        CDATA   #IMPLIED >
+
+<!ELEMENT Manifest (Reference+)  >
+<!ATTLIST Manifest  
+       Id      ID      #IMPLIED >
+
+<!ELEMENT SignatureProperties (SignatureProperty+)  >
+<!ATTLIST SignatureProperties  
+       Id      ID       #IMPLIED  >
+
+<!ELEMENT SignatureProperty (#PCDATA %SignatureProperty.ANY;)* >
+<!ATTLIST SignatureProperty  
+       Target  CDATA    #REQUIRED
+       Id      ID       #IMPLIED  >
+
+<!-- Algorithm Parameters -->
+
+<!ELEMENT HMACOutputLength (#PCDATA) >
+
+<!ELEMENT DSAKeyValue ((P, Q)?, G?, Y, J?, (Seed, PgenCounter)?) >
+<!ELEMENT P (#PCDATA) >
+<!ELEMENT Q (#PCDATA) >
+<!ELEMENT G (#PCDATA) >
+<!ELEMENT Y (#PCDATA) >
+<!ELEMENT J (#PCDATA) >
+<!ELEMENT Seed (#PCDATA) >
+<!ELEMENT PgenCounter (#PCDATA) >
+
+<!ELEMENT RSAKeyValue (Modulus, Exponent) > 
+<!ELEMENT Modulus (#PCDATA) >
+<!ELEMENT Exponent (#PCDATA) >
+
+
+
+
+
+
+
+
+<!ELEMENT policy-set (target?, assert*, (policy-set | policy)*) >
+<!ATTLIST policy-set
+    combine (deny-overrides|permit-overrides|first-matching-target) "deny-overrides"
+   id   ID      #IMPLIED 
+>
+
+<!ELEMENT policy (target?, assert*, rule*) >
+<!ATTLIST policy 
+    combine (deny-overrides|permit-overrides|first-applicable) "deny-overrides"
+    description CDATA #IMPLIED
+    id   ID     #IMPLIED 
+>
+
+<!ELEMENT assert (condition?, set*) >
+
+<!ELEMENT set EMPTY >
+<!ATTLIST set attr CDATA #REQUIRED >
+<!ATTLIST set value CDATA #REQUIRED >
+
+<!ELEMENT rule (condition?) >
+<!ATTLIST rule
+    effect (permit|prompt-blanket|prompt-session|prompt-oneshot|deny) "permit"
+>
+
+<!ELEMENT target (subject+) >
+
+<!ELEMENT subject (subject-match+) >
+
+<!ELEMENT condition ((condition | subject-match | resource-match | environment-match)+) >
+<!ATTLIST condition
+    combine (and|or) "and"
+>
+
+<!ENTITY % match-attrs '
+    attr CDATA #REQUIRED
+    match CDATA #IMPLIED
+    func (equal|glob|regexp) "glob"
+'>
+
+<!ELEMENT subject-match (#PCDATA)>
+<!ATTLIST subject-match %match-attrs; >
+
+<!ENTITY % match-model '
+    (#PCDATA | subject-attr | resource-attr | environment-attr)*
+'>
+
+<!ELEMENT resource-match %match-model;>
+<!ATTLIST resource-match %match-attrs;>
+
+<!ELEMENT environment-match %match-model;>
+<!ATTLIST environment-match %match-attrs;>
+
+<!ENTITY % attr-attrs 'attr CDATA #REQUIRED'>
+
+<!ELEMENT subject-attr EMPTY>
+<!ATTLIST subject-attr %attr-attrs;>
+
+<!ELEMENT resource-attr EMPTY>
+<!ATTLIST resource-attr %attr-attrs;>
+
+<!ELEMENT environment-attr EMPTY>
+<!ATTLIST environment-attr %attr-attrs;>
+
diff --git a/tests/ace/test-configuration/CMTest/active/pms_general-test.xml b/tests/ace/test-configuration/CMTest/active/pms_general-test.xml
new file mode 100644 (file)
index 0000000..ac55f33
--- /dev/null
@@ -0,0 +1,2510 @@
+<!DOCTYPE signed-policy SYSTEM "bondixml.dtd">
+
+<signed-policy>
+
+ <Signature Id="SignatureExample" xmlns="http://www.w3.org/2000/09/xmldsig#"> 
+   <SignedInfo> 
+   <CanonicalizationMethod Algorithm="http://www.w2.org/2006/12/xml-c14n11"/> 
+   <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> 
+   <Reference URI="Policy-1"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-2"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-3"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-4"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-5"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-6"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-7"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-8"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-9"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-10"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-11"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-12"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-13"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-14"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-15"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-16"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-17"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+ </SignedInfo> 
+   <SignatureValue>asdfkjlhxvczxnbcvnjahfjhsdfklahfdas</SignatureValue> 
+   <KeyInfo> 
+     <KeyValue>
+       <DSAKeyValue> 
+         <P> PValue </P><Q> QValue </Q><G> Gvalue </G><Y> laj?</Y>
+       </DSAKeyValue>
+       <RSAKeyValue>
+           <Modulus>
+               modulus
+           </Modulus>
+           <Exponent>
+               exponent
+           </Exponent>
+       </RSAKeyValue>
+     </KeyValue>
+     <X509Data>
+         <X509SubjectName> Subject name </X509SubjectName>
+         <X509SKI> SKI </X509SKI>
+     </X509Data>
+   </KeyInfo> 
+ </Signature>
+
+
+<policy-set id="Policy-1">      
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject
+            </subject-match>
+        </subject>
+        <subject>
+            <subject-match attr="id" match="subject2" />
+        </subject>
+    </target>
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject" />
+            </subject>
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>
+                <subject-match attr="version" match="3" />
+            </condition>
+        </rule>
+    </policy>        
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject2" />
+            </subject>
+        </target>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>    
+</policy-set>
+<policy-set >
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject3
+            </subject-match>                    
+        </subject>  
+        <subject>
+            <subject-match attr="id" match="subject4" />
+        </subject>                 
+    </target>
+    <policy>             
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                
+            </condition>
+        </rule>
+    </policy>        
+    <policy>            
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy> 
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject4
+                </subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set>    
+<policy-set id="Policy-2" combine="first-matching-target">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject5" />
+        </subject>                 
+        <subject>
+            <subject-match attr="id" match="subject6" />
+        </subject>                 
+    </target>
+    <policy>    
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject5
+                </subject-match>                    
+            </subject>              
+        </target>
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource5
+                </resource-match>                
+                <subject-match attr="version" match="5" />
+            </condition>
+        </rule>
+    </policy> 
+    <policy>             
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="resource-id">
+                    resource6
+                </resource-match>                
+                <subject-match attr="version" match="6" />
+            </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-3" combine="deny-overrides">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject7" />
+        </subject>                                 
+    </target>
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="and">
+                    <condition combine="or">
+                        <subject-match attr="version" match="7" />
+                        <subject-match attr="version" match="6" />
+                    </condition>
+                    <resource-match attr="author" match="author2" />
+                </condition>
+            </condition>
+        </rule>
+    </policy>   
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+    <policy>   
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+ </policy-set>
+
+<policy-set id="Policy-4" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+</policy-set>
+
+<policy-set id="Policy-5" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-6" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8c</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>
+                               <resource-match attr="r8v1" match="1" />
+                               <resource-match attr="r8v2" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+       <policy>
+               <rule effect="deny" />
+       </policy> 
+</policy-set>
+
+<policy-set id="Policy-7" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>
+                               <resource-match attr="r9a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-8" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b" match="777" func="equal" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-9"  combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9c</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>  
+                               <resource-match attr="r9c.scheme" match="http" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.authority" match="onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.scheme-authority" match="http://onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c" match="*" func="glob" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-10" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9d</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d" match="*" func="glob" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme-authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-11" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9e</subject-match>
+       </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-12" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9f</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-13" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9g</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-14" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9h</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-15" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-16" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10b</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-17" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10c</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10c" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10c" match="*" func="glob"/> 
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+
+<!-- justyna -->
+
+<!---    test 13    (old name: test 100)-->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s13</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 14    (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s14</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 15    (old name: test 102) -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri.host" match="//buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 16    (old name: test 103) -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s16</subject-match>
+                       <subject-match attr="uri.host" match="v.com.pl"/>
+                       
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 17    (old name: test 104)-->
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject4</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject5</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!---    test 18    (old name: test 105)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri" match="buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18b"/>
+                       <subject-match attr="uri" match="buu.s18b.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18c"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="uri" match="buu.s18c.pl"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 19    (old name: test 106)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.1</subject-match>                    
+                 <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.2</subject-match>                    
+                <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+
+<!---    test 20    (old name: test 107)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s20.1</subject-match>                    
+                <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+               <subject-match attr="id">s20.2</subject-match>                    
+               <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!-- justyna -->
+
+
+<!---    test 21    (old name: test 103 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s21</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 23    (old name: test 105 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s23</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 24    (old name: test 106 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s24</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <subject-match attr="version" match="5"/>
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.1    (old name: test 107 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.2    (old name: test 107 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.3    (old name: test 107 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 25.4    (old name: test 107 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 26.1    (old name: test 108 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.2    (old name: test 108 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.3    (old name: test 108 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 26.4    (old name: test 108 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.1    (old name: test 109 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.2    (old name: test 109a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.3    (old name: test 109b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.4    (old name: test 109c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 28    (old name: test 110 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s28</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 29    (old name: test 111 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s29</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.1    (old name: test 112 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.2    (old name: test 112a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.3    (old name: test 112b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.4    (old name: test 112c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+       
+</policy-set>
+
+
+
+<!---    test 31.1    (old name: test 113 U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 31.2.1    (old name: test 113a U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.2.2    (old name: test 113aa U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.3    (old name: test 113b U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.3</subject-match>
+               </subject>  
+       </target>
+
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+</policy-set>
+
+<!---    test 32.1    (old name: test 114 U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 32.2.1    (old name: test 114a U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.2.2    (old name: test 114aa U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.3    (old name: test 114b U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.1    (old name: test 115 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.2    (old name: test 115a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.3    (old name: test 115b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.3</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 34.1    (old name: test 116 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.1</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 34.2    (old name: test 116 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.2</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 35.1    (old name: test 117 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 35.2    (old name: test 117 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set>
+       <target>
+               <subject>
+                       <subject-match attr="id">org.tizen.widget.analogclock</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="http://helloheloo/"/>
+                       </condition>
+                </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 36    (old name: test 102 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s36</subject-match>
+                       <subject-match attr="version" match="5"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+
+<!---    test 37    (old name: test 108 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s37</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-oneshot">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 38    (old name: test 109 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 39    (old name: test 110 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!-- Maria -->
+<!-- testing different methods of policies and rules combining-->
+<!---    test 40    (old name: test 200 -->
+
+<!--- two opposite rules put into different policies in one policy set -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s40</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<!---    test 41    (old name: test 201 -->
+
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s41</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.1    (old name: test 202 -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.2    (old name: test 202b -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 43.1    (old name: test 203 -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+<!---    test 43.2    (old name: test 203b -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.1    (old name: test 204 -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.2    (old name: test 204b -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 45.1    (old name: test 205 -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of permit in contradiction to test 202 -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 45.2    (old name: test 205b -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of deny-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 46.1    (old name: test 206 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 46.2    (old name: test 206b -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 47.1    (old name: test 207 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 47.2    (old name: test 207b -->
+<!--- two opposite rules put into one policy -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 48 (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+<target>
+<subject>
+<subject-match attr="id">s48</subject-match>
+<subject-match attr="uri.host" match="www.test.pl"/>
+
+</subject>
+</target>
+<policy>
+<rule effect="permit">
+<condition combine="and">
+<resource-match attr="resource-id" match="device:pim.contacts"/>
+<!--<subject-match attr="uri" match="http://www.test.pl:80"/>-->
+</condition>
+</rule>
+</policy>
+</policy-set>
+
+</policy-set>
+
+</signed-policy> 
diff --git a/tests/ace/test-configuration/CMTest/pms_config.xml b/tests/ace/test-configuration/CMTest/pms_config.xml
new file mode 100644 (file)
index 0000000..fc9b0dc
--- /dev/null
@@ -0,0 +1,10 @@
+<?xml version="1.0" ?>
+<!DOCTYPE manager-settings SYSTEM "../config.dtd">
+<manager-settings>
+  <storage-path>/usr/etc/ace/CMTest/active</storage-path>
+  <policy-files>
+    <file active="true">pms_general-test.xml</file>
+  </policy-files>
+</manager-settings>
+
+
diff --git a/tests/ace/test-configuration/CMTest/pms_general-test.xml b/tests/ace/test-configuration/CMTest/pms_general-test.xml
new file mode 100644 (file)
index 0000000..ac55f33
--- /dev/null
@@ -0,0 +1,2510 @@
+<!DOCTYPE signed-policy SYSTEM "bondixml.dtd">
+
+<signed-policy>
+
+ <Signature Id="SignatureExample" xmlns="http://www.w3.org/2000/09/xmldsig#"> 
+   <SignedInfo> 
+   <CanonicalizationMethod Algorithm="http://www.w2.org/2006/12/xml-c14n11"/> 
+   <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> 
+   <Reference URI="Policy-1"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-2"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-3"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-4"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-5"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-6"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-7"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-8"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-9"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-10"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-11"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-12"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-13"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-14"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-15"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-16"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-17"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+ </SignedInfo> 
+   <SignatureValue>asdfkjlhxvczxnbcvnjahfjhsdfklahfdas</SignatureValue> 
+   <KeyInfo> 
+     <KeyValue>
+       <DSAKeyValue> 
+         <P> PValue </P><Q> QValue </Q><G> Gvalue </G><Y> laj?</Y>
+       </DSAKeyValue>
+       <RSAKeyValue>
+           <Modulus>
+               modulus
+           </Modulus>
+           <Exponent>
+               exponent
+           </Exponent>
+       </RSAKeyValue>
+     </KeyValue>
+     <X509Data>
+         <X509SubjectName> Subject name </X509SubjectName>
+         <X509SKI> SKI </X509SKI>
+     </X509Data>
+   </KeyInfo> 
+ </Signature>
+
+
+<policy-set id="Policy-1">      
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject
+            </subject-match>
+        </subject>
+        <subject>
+            <subject-match attr="id" match="subject2" />
+        </subject>
+    </target>
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject" />
+            </subject>
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>
+                <subject-match attr="version" match="3" />
+            </condition>
+        </rule>
+    </policy>        
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject2" />
+            </subject>
+        </target>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>    
+</policy-set>
+<policy-set >
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject3
+            </subject-match>                    
+        </subject>  
+        <subject>
+            <subject-match attr="id" match="subject4" />
+        </subject>                 
+    </target>
+    <policy>             
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                
+            </condition>
+        </rule>
+    </policy>        
+    <policy>            
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy> 
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject4
+                </subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set>    
+<policy-set id="Policy-2" combine="first-matching-target">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject5" />
+        </subject>                 
+        <subject>
+            <subject-match attr="id" match="subject6" />
+        </subject>                 
+    </target>
+    <policy>    
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject5
+                </subject-match>                    
+            </subject>              
+        </target>
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource5
+                </resource-match>                
+                <subject-match attr="version" match="5" />
+            </condition>
+        </rule>
+    </policy> 
+    <policy>             
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="resource-id">
+                    resource6
+                </resource-match>                
+                <subject-match attr="version" match="6" />
+            </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-3" combine="deny-overrides">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject7" />
+        </subject>                                 
+    </target>
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="and">
+                    <condition combine="or">
+                        <subject-match attr="version" match="7" />
+                        <subject-match attr="version" match="6" />
+                    </condition>
+                    <resource-match attr="author" match="author2" />
+                </condition>
+            </condition>
+        </rule>
+    </policy>   
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+    <policy>   
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+ </policy-set>
+
+<policy-set id="Policy-4" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+</policy-set>
+
+<policy-set id="Policy-5" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-6" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8c</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>
+                               <resource-match attr="r8v1" match="1" />
+                               <resource-match attr="r8v2" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+       <policy>
+               <rule effect="deny" />
+       </policy> 
+</policy-set>
+
+<policy-set id="Policy-7" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>
+                               <resource-match attr="r9a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-8" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b" match="777" func="equal" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-9"  combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9c</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>  
+                               <resource-match attr="r9c.scheme" match="http" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.authority" match="onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.scheme-authority" match="http://onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c" match="*" func="glob" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-10" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9d</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d" match="*" func="glob" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme-authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-11" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9e</subject-match>
+       </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-12" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9f</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-13" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9g</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-14" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9h</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-15" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-16" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10b</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-17" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10c</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10c" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10c" match="*" func="glob"/> 
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+
+<!-- justyna -->
+
+<!---    test 13    (old name: test 100)-->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s13</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 14    (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s14</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 15    (old name: test 102) -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri.host" match="//buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 16    (old name: test 103) -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s16</subject-match>
+                       <subject-match attr="uri.host" match="v.com.pl"/>
+                       
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 17    (old name: test 104)-->
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject4</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject5</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!---    test 18    (old name: test 105)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri" match="buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18b"/>
+                       <subject-match attr="uri" match="buu.s18b.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18c"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="uri" match="buu.s18c.pl"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 19    (old name: test 106)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.1</subject-match>                    
+                 <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.2</subject-match>                    
+                <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+
+<!---    test 20    (old name: test 107)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s20.1</subject-match>                    
+                <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+               <subject-match attr="id">s20.2</subject-match>                    
+               <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!-- justyna -->
+
+
+<!---    test 21    (old name: test 103 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s21</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 23    (old name: test 105 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s23</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 24    (old name: test 106 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s24</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <subject-match attr="version" match="5"/>
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.1    (old name: test 107 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.2    (old name: test 107 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.3    (old name: test 107 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 25.4    (old name: test 107 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 26.1    (old name: test 108 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.2    (old name: test 108 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.3    (old name: test 108 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 26.4    (old name: test 108 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.1    (old name: test 109 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.2    (old name: test 109a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.3    (old name: test 109b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.4    (old name: test 109c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 28    (old name: test 110 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s28</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 29    (old name: test 111 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s29</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.1    (old name: test 112 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.2    (old name: test 112a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.3    (old name: test 112b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.4    (old name: test 112c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+       
+</policy-set>
+
+
+
+<!---    test 31.1    (old name: test 113 U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 31.2.1    (old name: test 113a U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.2.2    (old name: test 113aa U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.3    (old name: test 113b U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.3</subject-match>
+               </subject>  
+       </target>
+
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+</policy-set>
+
+<!---    test 32.1    (old name: test 114 U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 32.2.1    (old name: test 114a U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.2.2    (old name: test 114aa U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.3    (old name: test 114b U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.1    (old name: test 115 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.2    (old name: test 115a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.3    (old name: test 115b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.3</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 34.1    (old name: test 116 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.1</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 34.2    (old name: test 116 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.2</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 35.1    (old name: test 117 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 35.2    (old name: test 117 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set>
+       <target>
+               <subject>
+                       <subject-match attr="id">org.tizen.widget.analogclock</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="http://helloheloo/"/>
+                       </condition>
+                </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 36    (old name: test 102 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s36</subject-match>
+                       <subject-match attr="version" match="5"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+
+<!---    test 37    (old name: test 108 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s37</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-oneshot">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 38    (old name: test 109 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 39    (old name: test 110 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!-- Maria -->
+<!-- testing different methods of policies and rules combining-->
+<!---    test 40    (old name: test 200 -->
+
+<!--- two opposite rules put into different policies in one policy set -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s40</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<!---    test 41    (old name: test 201 -->
+
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s41</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.1    (old name: test 202 -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.2    (old name: test 202b -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 43.1    (old name: test 203 -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+<!---    test 43.2    (old name: test 203b -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.1    (old name: test 204 -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.2    (old name: test 204b -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 45.1    (old name: test 205 -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of permit in contradiction to test 202 -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 45.2    (old name: test 205b -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of deny-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 46.1    (old name: test 206 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 46.2    (old name: test 206b -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 47.1    (old name: test 207 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 47.2    (old name: test 207b -->
+<!--- two opposite rules put into one policy -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 48 (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+<target>
+<subject>
+<subject-match attr="id">s48</subject-match>
+<subject-match attr="uri.host" match="www.test.pl"/>
+
+</subject>
+</target>
+<policy>
+<rule effect="permit">
+<condition combine="and">
+<resource-match attr="resource-id" match="device:pim.contacts"/>
+<!--<subject-match attr="uri" match="http://www.test.pl:80"/>-->
+</condition>
+</rule>
+</policy>
+</policy-set>
+
+</policy-set>
+
+</signed-policy> 
diff --git a/tests/ace/test-configuration/CMTest/policyTest1.xml b/tests/ace/test-configuration/CMTest/policyTest1.xml
new file mode 100644 (file)
index 0000000..ac55f33
--- /dev/null
@@ -0,0 +1,2510 @@
+<!DOCTYPE signed-policy SYSTEM "bondixml.dtd">
+
+<signed-policy>
+
+ <Signature Id="SignatureExample" xmlns="http://www.w3.org/2000/09/xmldsig#"> 
+   <SignedInfo> 
+   <CanonicalizationMethod Algorithm="http://www.w2.org/2006/12/xml-c14n11"/> 
+   <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> 
+   <Reference URI="Policy-1"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-2"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-3"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-4"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-5"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-6"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-7"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-8"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-9"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-10"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-11"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-12"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-13"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-14"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-15"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-16"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-17"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+ </SignedInfo> 
+   <SignatureValue>asdfkjlhxvczxnbcvnjahfjhsdfklahfdas</SignatureValue> 
+   <KeyInfo> 
+     <KeyValue>
+       <DSAKeyValue> 
+         <P> PValue </P><Q> QValue </Q><G> Gvalue </G><Y> laj?</Y>
+       </DSAKeyValue>
+       <RSAKeyValue>
+           <Modulus>
+               modulus
+           </Modulus>
+           <Exponent>
+               exponent
+           </Exponent>
+       </RSAKeyValue>
+     </KeyValue>
+     <X509Data>
+         <X509SubjectName> Subject name </X509SubjectName>
+         <X509SKI> SKI </X509SKI>
+     </X509Data>
+   </KeyInfo> 
+ </Signature>
+
+
+<policy-set id="Policy-1">      
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject
+            </subject-match>
+        </subject>
+        <subject>
+            <subject-match attr="id" match="subject2" />
+        </subject>
+    </target>
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject" />
+            </subject>
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>
+                <subject-match attr="version" match="3" />
+            </condition>
+        </rule>
+    </policy>        
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject2" />
+            </subject>
+        </target>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>    
+</policy-set>
+<policy-set >
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject3
+            </subject-match>                    
+        </subject>  
+        <subject>
+            <subject-match attr="id" match="subject4" />
+        </subject>                 
+    </target>
+    <policy>             
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                
+            </condition>
+        </rule>
+    </policy>        
+    <policy>            
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy> 
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject4
+                </subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set>    
+<policy-set id="Policy-2" combine="first-matching-target">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject5" />
+        </subject>                 
+        <subject>
+            <subject-match attr="id" match="subject6" />
+        </subject>                 
+    </target>
+    <policy>    
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject5
+                </subject-match>                    
+            </subject>              
+        </target>
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource5
+                </resource-match>                
+                <subject-match attr="version" match="5" />
+            </condition>
+        </rule>
+    </policy> 
+    <policy>             
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="resource-id">
+                    resource6
+                </resource-match>                
+                <subject-match attr="version" match="6" />
+            </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-3" combine="deny-overrides">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject7" />
+        </subject>                                 
+    </target>
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="and">
+                    <condition combine="or">
+                        <subject-match attr="version" match="7" />
+                        <subject-match attr="version" match="6" />
+                    </condition>
+                    <resource-match attr="author" match="author2" />
+                </condition>
+            </condition>
+        </rule>
+    </policy>   
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+    <policy>   
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+ </policy-set>
+
+<policy-set id="Policy-4" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+</policy-set>
+
+<policy-set id="Policy-5" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-6" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8c</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>
+                               <resource-match attr="r8v1" match="1" />
+                               <resource-match attr="r8v2" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+       <policy>
+               <rule effect="deny" />
+       </policy> 
+</policy-set>
+
+<policy-set id="Policy-7" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>
+                               <resource-match attr="r9a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-8" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b" match="777" func="equal" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-9"  combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9c</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>  
+                               <resource-match attr="r9c.scheme" match="http" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.authority" match="onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.scheme-authority" match="http://onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c" match="*" func="glob" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-10" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9d</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d" match="*" func="glob" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme-authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-11" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9e</subject-match>
+       </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-12" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9f</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-13" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9g</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-14" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9h</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-15" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-16" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10b</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-17" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10c</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10c" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10c" match="*" func="glob"/> 
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+
+<!-- justyna -->
+
+<!---    test 13    (old name: test 100)-->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s13</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 14    (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s14</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 15    (old name: test 102) -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri.host" match="//buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 16    (old name: test 103) -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s16</subject-match>
+                       <subject-match attr="uri.host" match="v.com.pl"/>
+                       
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 17    (old name: test 104)-->
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject4</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject5</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!---    test 18    (old name: test 105)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri" match="buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18b"/>
+                       <subject-match attr="uri" match="buu.s18b.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18c"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="uri" match="buu.s18c.pl"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 19    (old name: test 106)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.1</subject-match>                    
+                 <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.2</subject-match>                    
+                <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+
+<!---    test 20    (old name: test 107)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s20.1</subject-match>                    
+                <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+               <subject-match attr="id">s20.2</subject-match>                    
+               <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!-- justyna -->
+
+
+<!---    test 21    (old name: test 103 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s21</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 23    (old name: test 105 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s23</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 24    (old name: test 106 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s24</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <subject-match attr="version" match="5"/>
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.1    (old name: test 107 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.2    (old name: test 107 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.3    (old name: test 107 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 25.4    (old name: test 107 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 26.1    (old name: test 108 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.2    (old name: test 108 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.3    (old name: test 108 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 26.4    (old name: test 108 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.1    (old name: test 109 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.2    (old name: test 109a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.3    (old name: test 109b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.4    (old name: test 109c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 28    (old name: test 110 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s28</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 29    (old name: test 111 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s29</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.1    (old name: test 112 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.2    (old name: test 112a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.3    (old name: test 112b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.4    (old name: test 112c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+       
+</policy-set>
+
+
+
+<!---    test 31.1    (old name: test 113 U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 31.2.1    (old name: test 113a U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.2.2    (old name: test 113aa U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.3    (old name: test 113b U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.3</subject-match>
+               </subject>  
+       </target>
+
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+</policy-set>
+
+<!---    test 32.1    (old name: test 114 U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 32.2.1    (old name: test 114a U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.2.2    (old name: test 114aa U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.3    (old name: test 114b U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.1    (old name: test 115 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.2    (old name: test 115a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.3    (old name: test 115b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.3</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 34.1    (old name: test 116 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.1</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 34.2    (old name: test 116 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.2</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 35.1    (old name: test 117 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 35.2    (old name: test 117 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set>
+       <target>
+               <subject>
+                       <subject-match attr="id">org.tizen.widget.analogclock</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="http://helloheloo/"/>
+                       </condition>
+                </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 36    (old name: test 102 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s36</subject-match>
+                       <subject-match attr="version" match="5"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+
+<!---    test 37    (old name: test 108 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s37</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-oneshot">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 38    (old name: test 109 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 39    (old name: test 110 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!-- Maria -->
+<!-- testing different methods of policies and rules combining-->
+<!---    test 40    (old name: test 200 -->
+
+<!--- two opposite rules put into different policies in one policy set -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s40</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<!---    test 41    (old name: test 201 -->
+
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s41</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.1    (old name: test 202 -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.2    (old name: test 202b -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 43.1    (old name: test 203 -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+<!---    test 43.2    (old name: test 203b -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.1    (old name: test 204 -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.2    (old name: test 204b -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 45.1    (old name: test 205 -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of permit in contradiction to test 202 -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 45.2    (old name: test 205b -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of deny-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 46.1    (old name: test 206 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 46.2    (old name: test 206b -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 47.1    (old name: test 207 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 47.2    (old name: test 207b -->
+<!--- two opposite rules put into one policy -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 48 (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+<target>
+<subject>
+<subject-match attr="id">s48</subject-match>
+<subject-match attr="uri.host" match="www.test.pl"/>
+
+</subject>
+</target>
+<policy>
+<rule effect="permit">
+<condition combine="and">
+<resource-match attr="resource-id" match="device:pim.contacts"/>
+<!--<subject-match attr="uri" match="http://www.test.pl:80"/>-->
+</condition>
+</rule>
+</policy>
+</policy-set>
+
+</policy-set>
+
+</signed-policy> 
diff --git a/tests/ace/test-configuration/CMTest/policyTest2.xml b/tests/ace/test-configuration/CMTest/policyTest2.xml
new file mode 100644 (file)
index 0000000..ac55f33
--- /dev/null
@@ -0,0 +1,2510 @@
+<!DOCTYPE signed-policy SYSTEM "bondixml.dtd">
+
+<signed-policy>
+
+ <Signature Id="SignatureExample" xmlns="http://www.w3.org/2000/09/xmldsig#"> 
+   <SignedInfo> 
+   <CanonicalizationMethod Algorithm="http://www.w2.org/2006/12/xml-c14n11"/> 
+   <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> 
+   <Reference URI="Policy-1"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-2"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-3"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-4"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-5"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-6"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-7"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-8"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-9"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-10"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-11"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-12"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-13"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-14"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-15"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-16"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-17"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+ </SignedInfo> 
+   <SignatureValue>asdfkjlhxvczxnbcvnjahfjhsdfklahfdas</SignatureValue> 
+   <KeyInfo> 
+     <KeyValue>
+       <DSAKeyValue> 
+         <P> PValue </P><Q> QValue </Q><G> Gvalue </G><Y> laj?</Y>
+       </DSAKeyValue>
+       <RSAKeyValue>
+           <Modulus>
+               modulus
+           </Modulus>
+           <Exponent>
+               exponent
+           </Exponent>
+       </RSAKeyValue>
+     </KeyValue>
+     <X509Data>
+         <X509SubjectName> Subject name </X509SubjectName>
+         <X509SKI> SKI </X509SKI>
+     </X509Data>
+   </KeyInfo> 
+ </Signature>
+
+
+<policy-set id="Policy-1">      
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject
+            </subject-match>
+        </subject>
+        <subject>
+            <subject-match attr="id" match="subject2" />
+        </subject>
+    </target>
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject" />
+            </subject>
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>
+                <subject-match attr="version" match="3" />
+            </condition>
+        </rule>
+    </policy>        
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject2" />
+            </subject>
+        </target>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>    
+</policy-set>
+<policy-set >
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject3
+            </subject-match>                    
+        </subject>  
+        <subject>
+            <subject-match attr="id" match="subject4" />
+        </subject>                 
+    </target>
+    <policy>             
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                
+            </condition>
+        </rule>
+    </policy>        
+    <policy>            
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy> 
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject4
+                </subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set>    
+<policy-set id="Policy-2" combine="first-matching-target">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject5" />
+        </subject>                 
+        <subject>
+            <subject-match attr="id" match="subject6" />
+        </subject>                 
+    </target>
+    <policy>    
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject5
+                </subject-match>                    
+            </subject>              
+        </target>
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource5
+                </resource-match>                
+                <subject-match attr="version" match="5" />
+            </condition>
+        </rule>
+    </policy> 
+    <policy>             
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="resource-id">
+                    resource6
+                </resource-match>                
+                <subject-match attr="version" match="6" />
+            </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-3" combine="deny-overrides">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject7" />
+        </subject>                                 
+    </target>
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="and">
+                    <condition combine="or">
+                        <subject-match attr="version" match="7" />
+                        <subject-match attr="version" match="6" />
+                    </condition>
+                    <resource-match attr="author" match="author2" />
+                </condition>
+            </condition>
+        </rule>
+    </policy>   
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+    <policy>   
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+ </policy-set>
+
+<policy-set id="Policy-4" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+</policy-set>
+
+<policy-set id="Policy-5" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-6" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8c</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>
+                               <resource-match attr="r8v1" match="1" />
+                               <resource-match attr="r8v2" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+       <policy>
+               <rule effect="deny" />
+       </policy> 
+</policy-set>
+
+<policy-set id="Policy-7" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>
+                               <resource-match attr="r9a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-8" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b" match="777" func="equal" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-9"  combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9c</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>  
+                               <resource-match attr="r9c.scheme" match="http" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.authority" match="onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.scheme-authority" match="http://onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c" match="*" func="glob" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-10" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9d</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d" match="*" func="glob" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme-authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-11" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9e</subject-match>
+       </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-12" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9f</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-13" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9g</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-14" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9h</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-15" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-16" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10b</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-17" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10c</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10c" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10c" match="*" func="glob"/> 
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+
+<!-- justyna -->
+
+<!---    test 13    (old name: test 100)-->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s13</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 14    (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s14</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 15    (old name: test 102) -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri.host" match="//buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 16    (old name: test 103) -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s16</subject-match>
+                       <subject-match attr="uri.host" match="v.com.pl"/>
+                       
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 17    (old name: test 104)-->
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject4</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject5</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!---    test 18    (old name: test 105)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri" match="buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18b"/>
+                       <subject-match attr="uri" match="buu.s18b.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18c"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="uri" match="buu.s18c.pl"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 19    (old name: test 106)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.1</subject-match>                    
+                 <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.2</subject-match>                    
+                <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+
+<!---    test 20    (old name: test 107)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s20.1</subject-match>                    
+                <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+               <subject-match attr="id">s20.2</subject-match>                    
+               <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!-- justyna -->
+
+
+<!---    test 21    (old name: test 103 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s21</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 23    (old name: test 105 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s23</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 24    (old name: test 106 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s24</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <subject-match attr="version" match="5"/>
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.1    (old name: test 107 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.2    (old name: test 107 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.3    (old name: test 107 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 25.4    (old name: test 107 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 26.1    (old name: test 108 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.2    (old name: test 108 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.3    (old name: test 108 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 26.4    (old name: test 108 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.1    (old name: test 109 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.2    (old name: test 109a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.3    (old name: test 109b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.4    (old name: test 109c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 28    (old name: test 110 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s28</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 29    (old name: test 111 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s29</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.1    (old name: test 112 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.2    (old name: test 112a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.3    (old name: test 112b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.4    (old name: test 112c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+       
+</policy-set>
+
+
+
+<!---    test 31.1    (old name: test 113 U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 31.2.1    (old name: test 113a U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.2.2    (old name: test 113aa U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.3    (old name: test 113b U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.3</subject-match>
+               </subject>  
+       </target>
+
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+</policy-set>
+
+<!---    test 32.1    (old name: test 114 U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 32.2.1    (old name: test 114a U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.2.2    (old name: test 114aa U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.3    (old name: test 114b U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.1    (old name: test 115 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.2    (old name: test 115a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.3    (old name: test 115b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.3</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 34.1    (old name: test 116 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.1</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 34.2    (old name: test 116 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.2</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 35.1    (old name: test 117 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 35.2    (old name: test 117 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set>
+       <target>
+               <subject>
+                       <subject-match attr="id">org.tizen.widget.analogclock</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="http://helloheloo/"/>
+                       </condition>
+                </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 36    (old name: test 102 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s36</subject-match>
+                       <subject-match attr="version" match="5"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+
+<!---    test 37    (old name: test 108 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s37</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-oneshot">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 38    (old name: test 109 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 39    (old name: test 110 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!-- Maria -->
+<!-- testing different methods of policies and rules combining-->
+<!---    test 40    (old name: test 200 -->
+
+<!--- two opposite rules put into different policies in one policy set -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s40</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<!---    test 41    (old name: test 201 -->
+
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s41</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.1    (old name: test 202 -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.2    (old name: test 202b -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 43.1    (old name: test 203 -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+<!---    test 43.2    (old name: test 203b -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.1    (old name: test 204 -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.2    (old name: test 204b -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 45.1    (old name: test 205 -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of permit in contradiction to test 202 -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 45.2    (old name: test 205b -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of deny-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 46.1    (old name: test 206 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 46.2    (old name: test 206b -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 47.1    (old name: test 207 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 47.2    (old name: test 207b -->
+<!--- two opposite rules put into one policy -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 48 (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+<target>
+<subject>
+<subject-match attr="id">s48</subject-match>
+<subject-match attr="uri.host" match="www.test.pl"/>
+
+</subject>
+</target>
+<policy>
+<rule effect="permit">
+<condition combine="and">
+<resource-match attr="resource-id" match="device:pim.contacts"/>
+<!--<subject-match attr="uri" match="http://www.test.pl:80"/>-->
+</condition>
+</rule>
+</policy>
+</policy-set>
+
+</policy-set>
+
+</signed-policy> 
diff --git a/tests/ace/test-configuration/CMTest/policyTest3.xml b/tests/ace/test-configuration/CMTest/policyTest3.xml
new file mode 100644 (file)
index 0000000..ac55f33
--- /dev/null
@@ -0,0 +1,2510 @@
+<!DOCTYPE signed-policy SYSTEM "bondixml.dtd">
+
+<signed-policy>
+
+ <Signature Id="SignatureExample" xmlns="http://www.w3.org/2000/09/xmldsig#"> 
+   <SignedInfo> 
+   <CanonicalizationMethod Algorithm="http://www.w2.org/2006/12/xml-c14n11"/> 
+   <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> 
+   <Reference URI="Policy-1"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-2"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-3"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-4"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-5"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-6"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-7"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-8"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-9"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-10"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-11"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-12"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-13"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-14"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-15"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-16"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+   <Reference URI="Policy-17"> 
+     <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> 
+     <DigestValue>dGhpcyBpcyBub3QgYSBzaWduYXR1cmUK...</DigestValue> 
+   </Reference> 
+ </SignedInfo> 
+   <SignatureValue>asdfkjlhxvczxnbcvnjahfjhsdfklahfdas</SignatureValue> 
+   <KeyInfo> 
+     <KeyValue>
+       <DSAKeyValue> 
+         <P> PValue </P><Q> QValue </Q><G> Gvalue </G><Y> laj?</Y>
+       </DSAKeyValue>
+       <RSAKeyValue>
+           <Modulus>
+               modulus
+           </Modulus>
+           <Exponent>
+               exponent
+           </Exponent>
+       </RSAKeyValue>
+     </KeyValue>
+     <X509Data>
+         <X509SubjectName> Subject name </X509SubjectName>
+         <X509SKI> SKI </X509SKI>
+     </X509Data>
+   </KeyInfo> 
+ </Signature>
+
+
+<policy-set id="Policy-1">      
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject
+            </subject-match>
+        </subject>
+        <subject>
+            <subject-match attr="id" match="subject2" />
+        </subject>
+    </target>
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject" />
+            </subject>
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>
+                <subject-match attr="version" match="3" />
+            </condition>
+        </rule>
+    </policy>        
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject2" />
+            </subject>
+        </target>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>    
+</policy-set>
+<policy-set >
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject3
+            </subject-match>                    
+        </subject>  
+        <subject>
+            <subject-match attr="id" match="subject4" />
+        </subject>                 
+    </target>
+    <policy>             
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                
+            </condition>
+        </rule>
+    </policy>        
+    <policy>            
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy> 
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject4
+                </subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set>    
+<policy-set id="Policy-2" combine="first-matching-target">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject5" />
+        </subject>                 
+        <subject>
+            <subject-match attr="id" match="subject6" />
+        </subject>                 
+    </target>
+    <policy>    
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject5
+                </subject-match>                    
+            </subject>              
+        </target>
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource5
+                </resource-match>                
+                <subject-match attr="version" match="5" />
+            </condition>
+        </rule>
+    </policy> 
+    <policy>             
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="resource-id">
+                    resource6
+                </resource-match>                
+                <subject-match attr="version" match="6" />
+            </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-3" combine="deny-overrides">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject7" />
+        </subject>                                 
+    </target>
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="and">
+                    <condition combine="or">
+                        <subject-match attr="version" match="7" />
+                        <subject-match attr="version" match="6" />
+                    </condition>
+                    <resource-match attr="author" match="author2" />
+                </condition>
+            </condition>
+        </rule>
+    </policy>   
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+    <policy>   
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+ </policy-set>
+
+<policy-set id="Policy-4" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+</policy-set>
+
+<policy-set id="Policy-5" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-6" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8c</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>
+                               <resource-match attr="r8v1" match="1" />
+                               <resource-match attr="r8v2" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+       <policy>
+               <rule effect="deny" />
+       </policy> 
+</policy-set>
+
+<policy-set id="Policy-7" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>
+                               <resource-match attr="r9a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-8" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b" match="777" func="equal" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-9"  combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9c</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>  
+                               <resource-match attr="r9c.scheme" match="http" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.authority" match="onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.scheme-authority" match="http://onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c" match="*" func="glob" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-10" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9d</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d" match="*" func="glob" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme-authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-11" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9e</subject-match>
+       </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-12" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9f</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-13" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9g</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-14" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9h</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-15" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-16" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10b</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-17" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10c</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10c" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10c" match="*" func="glob"/> 
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+
+<!-- justyna -->
+
+<!---    test 13    (old name: test 100)-->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s13</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 14    (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s14</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 15    (old name: test 102) -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri.host" match="//buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 16    (old name: test 103) -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s16</subject-match>
+                       <subject-match attr="uri.host" match="v.com.pl"/>
+                       
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 17    (old name: test 104)-->
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject4</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject5</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!---    test 18    (old name: test 105)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri" match="buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18b"/>
+                       <subject-match attr="uri" match="buu.s18b.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18c"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="uri" match="buu.s18c.pl"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 19    (old name: test 106)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.1</subject-match>                    
+                 <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.2</subject-match>                    
+                <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+
+<!---    test 20    (old name: test 107)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s20.1</subject-match>                    
+                <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+               <subject-match attr="id">s20.2</subject-match>                    
+               <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!-- justyna -->
+
+
+<!---    test 21    (old name: test 103 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s21</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 23    (old name: test 105 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s23</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 24    (old name: test 106 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s24</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <subject-match attr="version" match="5"/>
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.1    (old name: test 107 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.2    (old name: test 107 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.3    (old name: test 107 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 25.4    (old name: test 107 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 26.1    (old name: test 108 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.2    (old name: test 108 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.3    (old name: test 108 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 26.4    (old name: test 108 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.1    (old name: test 109 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.2    (old name: test 109a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.3    (old name: test 109b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.4    (old name: test 109c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 28    (old name: test 110 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s28</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 29    (old name: test 111 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s29</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.1    (old name: test 112 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.2    (old name: test 112a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.3    (old name: test 112b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.4    (old name: test 112c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+       
+</policy-set>
+
+
+
+<!---    test 31.1    (old name: test 113 U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 31.2.1    (old name: test 113a U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.2.2    (old name: test 113aa U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.3    (old name: test 113b U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.3</subject-match>
+               </subject>  
+       </target>
+
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+</policy-set>
+
+<!---    test 32.1    (old name: test 114 U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 32.2.1    (old name: test 114a U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.2.2    (old name: test 114aa U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.3    (old name: test 114b U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.1    (old name: test 115 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.2    (old name: test 115a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.3    (old name: test 115b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.3</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 34.1    (old name: test 116 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.1</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 34.2    (old name: test 116 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.2</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 35.1    (old name: test 117 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 35.2    (old name: test 117 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set>
+       <target>
+               <subject>
+                       <subject-match attr="id">org.tizen.widget.analogclock</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="http://helloheloo/"/>
+                       </condition>
+                </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 36    (old name: test 102 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s36</subject-match>
+                       <subject-match attr="version" match="5"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+
+<!---    test 37    (old name: test 108 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s37</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-oneshot">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 38    (old name: test 109 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 39    (old name: test 110 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!-- Maria -->
+<!-- testing different methods of policies and rules combining-->
+<!---    test 40    (old name: test 200 -->
+
+<!--- two opposite rules put into different policies in one policy set -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s40</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<!---    test 41    (old name: test 201 -->
+
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s41</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.1    (old name: test 202 -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.2    (old name: test 202b -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 43.1    (old name: test 203 -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+<!---    test 43.2    (old name: test 203b -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.1    (old name: test 204 -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.2    (old name: test 204b -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 45.1    (old name: test 205 -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of permit in contradiction to test 202 -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 45.2    (old name: test 205b -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of deny-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 46.1    (old name: test 206 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 46.2    (old name: test 206b -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 47.1    (old name: test 207 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 47.2    (old name: test 207b -->
+<!--- two opposite rules put into one policy -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 48 (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+<target>
+<subject>
+<subject-match attr="id">s48</subject-match>
+<subject-match attr="uri.host" match="www.test.pl"/>
+
+</subject>
+</target>
+<policy>
+<rule effect="permit">
+<condition combine="and">
+<resource-match attr="resource-id" match="device:pim.contacts"/>
+<!--<subject-match attr="uri" match="http://www.test.pl:80"/>-->
+</condition>
+</rule>
+</policy>
+</policy-set>
+
+</policy-set>
+
+</signed-policy> 
diff --git a/tests/ace/test-configuration/CMakeLists.txt b/tests/ace/test-configuration/CMakeLists.txt
new file mode 100644 (file)
index 0000000..550ff26
--- /dev/null
@@ -0,0 +1,42 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/policy-example.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/policy-wac-2.0.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/attr_policy-example.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/policy-example2.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/policy-example3.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/policy_example.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/general-test.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/interceptpolicy.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/policy-test.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/policy-test-gsettings.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/attre_config.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/attr_policy-example1.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/attr_policy-example2.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/attr_policy-example3.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/attr_policy-example4.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/attr_policy-example5.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/attr_policy-example6.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/attr_policy-example7.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/attr_policy-example8.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/undefined-test.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/WAC2.0Policy-test.xml
+    ${PROJECT_SOURCE_DIR}/tests/ace/test-configuration/TizenPolicy-test.xml
+    DESTINATION /usr/etc/ace
+    PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ GROUP_WRITE
+  )
+
+ADD_SUBDIRECTORY(CMTest)
diff --git a/tests/ace/test-configuration/TizenPolicy-test.xml b/tests/ace/test-configuration/TizenPolicy-test.xml
new file mode 100644 (file)
index 0000000..179f250
--- /dev/null
@@ -0,0 +1,23 @@
+<policy-set id="Policy-1" combine="first-matching-target">
+<policy>
+    <target>
+        <subject>
+            <subject-match attr="id">tizen</subject-match>
+        </subject>  
+    </target>
+    <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">tizen1resource</resource-match>    
+            </condition>
+    </rule>
+    <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">tizen2resource</resource-match>    
+            </condition>
+    </rule>
+</policy>
+<policy>   
+    <rule effect="deny" />
+</policy>
+</policy-set>
+
diff --git a/tests/ace/test-configuration/WAC2.0Policy-test.xml b/tests/ace/test-configuration/WAC2.0Policy-test.xml
new file mode 100644 (file)
index 0000000..bd2fc8a
--- /dev/null
@@ -0,0 +1,23 @@
+<policy-set id="Policy-1" combine="first-matching-target">
+<policy>
+    <target>
+        <subject>
+            <subject-match attr="id">wac</subject-match>
+        </subject>  
+    </target>
+    <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">wac1resource</resource-match>    
+            </condition>
+    </rule>
+    <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">wac2resource</resource-match>    
+            </condition>
+    </rule>
+</policy>
+<policy>   
+    <rule effect="permit" />
+</policy>
+</policy-set>
+
diff --git a/tests/ace/test-configuration/attr_policy-example.xml b/tests/ace/test-configuration/attr_policy-example.xml
new file mode 100644 (file)
index 0000000..8f0687f
--- /dev/null
@@ -0,0 +1,50 @@
+ <policy-set id="Policy-1" combine="first-matching-target">
+    
+    <policy>
+          <target>
+             <subject>
+                 <subject-match attr="name" match="analogclock"/>               
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="resource-id">
+                     device.simcard 
+                 </resource-match>
+             </condition>
+         </rule>
+     </policy>        
+     
+     <policy>
+         <target>
+             <subject>
+                 <subject-match attr="name" match="memo" />             
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="resource-id">
+                    file.write 
+                 </resource-match>
+                 <subject-match attr="name" match="memo" />
+             </condition>
+         </rule>
+     </policy>   
+   
+     <policy>
+         <target>
+             <subject>
+                 <subject-match attr="name" match="phonesearch" />              
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="resource-id">
+                     pim.contact 
+                 </resource-match>
+                 <subject-match attr="name" match="phonesearch" />
+             </condition>
+         </rule>
+     </policy> 
+
+ </policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/attr_policy-example1.xml b/tests/ace/test-configuration/attr_policy-example1.xml
new file mode 100644 (file)
index 0000000..a4869c5
--- /dev/null
@@ -0,0 +1,97 @@
+ <policy-set id="Policy-1" combine="first-matching-target">
+    
+
+       <policy>
+          <target>
+             <subject>
+                 <subject-match attr="uri.host" match="freebeer.evil.com" />
+                               <subject-match attr="version" match="4" />
+                
+          </subject>
+         </target>
+      <rule effect="permit">
+             <condition>
+                               <resource-match attr="r8v2" match="2" />
+             </condition>
+         </rule>
+
+     </policy>        
+
+
+
+       <policy>
+          <target>
+             <subject>
+                 <subject-match attr="key-root-trust" match="manufacturer" />
+               
+          </subject>
+         </target>
+      <rule effect="permit">
+             <condition>
+                                       <resource-match attr="author" match="author3" />              
+            </condition>
+         </rule>
+
+     </policy>        
+
+       <policy>
+          <target>
+             <subject>
+                 <subject-match attr="id" match="urn:megacorp:widget:anapp" />
+                
+          </subject>
+         </target>
+      <rule effect="permit">
+             <condition>
+                                       <resource-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />               
+            </condition>
+         </rule>
+
+     </policy>        
+
+       <policy>
+          <target>
+             <subject>
+                <subject-match attr="signer-id" match="7zha89%49x£$" />
+               
+          </subject>
+         </target>
+      <rule effect="permit">
+             <condition>
+                               <resource-match attr="r9b.authority" match="http://onet.pl:80/test.html" />         
+             </condition>
+         </rule>
+
+     </policy>        
+  
+       <policy>
+          <target>
+             <subject>
+                 <subject-match attr="id" match="urn:megacorp:widget:anapp" />
+                
+          </subject>
+         </target>
+      <rule effect="permit">
+             <condition>
+                                       <resource-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />               
+            </condition>
+         </rule>
+
+     </policy>        
+
+       <policy>
+          <target>
+             <subject>
+                <subject-match attr="signer-id" match="7zha89%49x£$" />
+               
+          </subject>
+         </target>
+      <rule effect="permit">
+             <condition>
+                       <resource-match attr="r9c.scheme-authority" match="http://onet.pl" />
+                        </condition>
+         </rule>
+
+     </policy>   
+
+    </policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/attr_policy-example2.xml b/tests/ace/test-configuration/attr_policy-example2.xml
new file mode 100644 (file)
index 0000000..e7a85be
--- /dev/null
@@ -0,0 +1,55 @@
+<policy-set id="Policy-3" combine="deny-overrides">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject7" />
+        </subject>                                 
+    </target>
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="and">
+                    <condition combine="or">
+                        <subject-match attr="version" match="7" />
+                        <subject-match attr="version" match="6" />
+                    </condition>
+                    <resource-match attr="author" match="author2" />
+                </condition>
+            </condition>
+        </rule>
+    </policy>   
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+    <policy>   
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+ </policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/attr_policy-example3.xml b/tests/ace/test-configuration/attr_policy-example3.xml
new file mode 100644 (file)
index 0000000..4d15108
--- /dev/null
@@ -0,0 +1,128 @@
+<policy-set id="Policy-1">      
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject
+            </subject-match>
+        </subject>
+        <subject>
+            <subject-match attr="id" match="subject2" />
+        </subject>
+    </target>
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject" />
+            </subject>
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>
+                <subject-match attr="version" match="3" />
+            </condition>
+        </rule>
+    </policy>        
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject2" />
+            </subject>
+        </target>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>    
+</policy-set>
+<policy-set >
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject3
+            </subject-match>                    
+        </subject>  
+        <subject>
+            <subject-match attr="id" match="subject4" />
+        </subject>                 
+    </target>
+    <policy>             
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                
+            </condition>
+        </rule>
+    </policy>        
+    <policy>            
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy> 
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject4
+                </subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set>   
+   
+<policy-set id="Policy-2" combine="first-matching-target">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject5" />
+        </subject>                 
+        <subject>
+            <subject-match attr="id" match="subject6" />
+        </subject>                 
+    </target>
+    <policy>    
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject5
+                </subject-match>                    
+            </subject>              
+        </target>
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource5
+                </resource-match>                
+                <subject-match attr="version" match="5" />
+            </condition>
+        </rule>
+    </policy> 
+    <policy>             
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="author">
+                    resource6
+                </resource-match>                
+                <subject-match attr="version" match="6" />
+            </condition>
+        </rule>
+    </policy>  
+</policy-set>
+</policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/attr_policy-example4.xml b/tests/ace/test-configuration/attr_policy-example4.xml
new file mode 100644 (file)
index 0000000..f709233
--- /dev/null
@@ -0,0 +1,102 @@
+<policy-set id="Policy-3" combine="deny-overrides">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject7" />
+        </subject>                                 
+    </target>
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="and">
+                    <condition combine="or">
+                        <subject-match attr="version" match="7" />
+                        <subject-match attr="version" match="6" />
+                    </condition>
+                    <resource-match attr="author" match="author2" />
+                </condition>
+            </condition>
+        </rule>
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="and">
+                    <condition combine="or">
+                        <subject-match attr="version" match="7" />
+                        <subject-match attr="version" match="6" />
+                    </condition>
+                    <environment-match attr="author" match="author2" />
+                </condition>
+            </condition>
+        </rule>
+
+
+    </policy>   
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+
+
+
+    </policy> 
+    <policy>   
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <environment-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+         <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <environment-match attr="ver" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+   </policy> 
+ </policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/attr_policy-example5.xml b/tests/ace/test-configuration/attr_policy-example5.xml
new file mode 100644 (file)
index 0000000..f9c837e
--- /dev/null
@@ -0,0 +1,43 @@
+<policy-set id="Policy-3" combine="deny-overrides">
+
+ <policy>
+          <target>
+             <subject>
+                 <subject-match attr="name" match="analogclock"/>
+                 <subject-match attr="uri.host" match="freebeer.evil.com" />
+                 <subject-match attr="key-root-trust" match="manufacturer" />
+                 <subject-match attr="id" match="urn:megacorp:widget:anapp" />
+                 <subject-match attr="signer-id" match="7zha89%49xL$" />
+                 <subject-match attr="version" match="5"/>
+
+          </subject>
+         </target>
+      <rule effect="permit">
+             <condition>
+               <resource-match attr="resource-id">device.simcard</resource-match>
+               <resource-match attr="r8v2" match="2" />
+               <resource-match attr="author" match="author3" />
+              <resource-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+               <resource-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+               <resource-match attr="r9c.scheme-authority" match="http://onet.pl" />
+               
+              <environment-match attr="resource-id">device.simcard</environment-match>
+               <environment-match attr="r8v2" match="2" />
+               <environment-match attr="author" match="author3" />
+              <environment-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+               <environment-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+               <environment-match attr="r9c.scheme-authority" match="http://onet.pl" />
+                               
+              <subject-match attr="resource-id">device.simcard</subject-match>
+               <subject-match attr="r8v2" match="2" />
+               <subject-match attr="author" match="author3" />
+              <subject-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+               <subject-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+               <subject-match attr="r9c.scheme-authority" match="http://onet.pl" />
+
+           </condition>
+         </rule>
+     </policy>
+
+
+</policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/attr_policy-example6.xml b/tests/ace/test-configuration/attr_policy-example6.xml
new file mode 100644 (file)
index 0000000..7a4c709
--- /dev/null
@@ -0,0 +1,41 @@
+<policy-set id="Policy-3" combine="deny-overrides">
+
+<policy>
+    <target>
+        <subject>
+            <subject-match attr="s-name" match="analogclock"/>
+            <subject-match attr="s-uri.host" match="freebeer.evil.com" />
+            <subject-match attr="s-key-root-trust" match="manufacturer" />
+            <subject-match attr="s-id" match="urn:megacorp:widget:anapp" />
+            <subject-match attr="s-signer-id" match="7zha89%49xL$" />
+            <subject-match attr="s-version" match="5"/>
+        </subject>
+    </target>
+    <rule effect="permit">
+        <condition>
+            <resource-match attr="r-resource-id">device.simcard</resource-match>
+            <resource-match attr="r-r8v2" match="2" />
+            <resource-match attr="r-author" match="author3" />
+            <resource-match attr="r-r9a.scheme" match="http://onet.pl:80/test.html" />
+            <resource-match attr="r-r9b.authority" match="http://onet.pl:80/test.html" />
+            <resource-match attr="r-r9c.scheme-authority" match="http://onet.pl" />
+
+            <environment-match attr="e-resource-id">device.simcard</environment-match>
+            <environment-match attr="e-r8v2" match="2" />
+            <environment-match attr="e-author" match="author3" />
+            <environment-match attr="e-r9a.scheme" match="http://onet.pl:80/test.html" />
+            <environment-match attr="e-r9b.authority" match="http://onet.pl:80/test.html" />
+            <environment-match attr="e-r9c.scheme-authority" match="http://onet.pl" />
+
+            <subject-match attr="s-resource-id">device.simcard</subject-match>
+            <subject-match attr="s-r8v2" match="2" />
+            <subject-match attr="s-author" match="author3" />
+            <subject-match attr="s-r9a.scheme" match="http://onet.pl:80/test.html" />
+            <subject-match attr="s-r9b.authority" match="http://onet.pl:80/test.html" />
+            <subject-match attr="s-r9c.scheme-authority" match="http://onet.pl" />
+        </condition>
+    </rule>
+</policy>
+
+
+</policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/attr_policy-example7.xml b/tests/ace/test-configuration/attr_policy-example7.xml
new file mode 100644 (file)
index 0000000..15907f9
--- /dev/null
@@ -0,0 +1,54 @@
+<policy-set id="Policy-3" combine="deny-overrides">
+
+ <policy>
+          <target>
+             <subject>
+                 <subject-match attr="name" match="analogclock"/>
+                 <subject-match attr="uri.host" match="freebeer.evil.com" />
+                 <subject-match attr="key-root-trust" match="manufacturer" />
+                 <subject-match attr="id" match="urn:megacorp:widget:anapp" />
+                 <subject-match attr="signer-id" match="7zha89%49xL$" />
+                 <subject-match attr="version" match="5"/>
+
+          </subject>
+         </target>
+      <rule effect="permit">
+             <condition>
+                       
+                          <subject-match attr="resource-id">device.simcard</subject-match>
+               <subject-match attr="r8v2" match="2" />
+               <subject-match attr="author" match="author3" />
+                          <subject-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+               <subject-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+               <subject-match attr="r9c.scheme-authority" match="http://onet.pl" />
+
+                       </condition>
+         </rule>
+     <rule effect="permit">
+             <condition>
+              
+                          <environment-match attr="resource-id">device.simcard</environment-match>
+               <environment-match attr="r8v2" match="2" />
+               <environment-match attr="author" match="author3" />
+                          <environment-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+               <environment-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+               <environment-match attr="r9c.scheme-authority" match="http://onet.pl" />
+                               
+                       </condition>
+         </rule>
+      <rule effect="permit">
+             <condition>
+               <resource-match attr="resource-id">device.simcard</resource-match>
+               <resource-match attr="r8v2" match="2" />
+               <resource-match attr="author" match="author3" />
+                          <resource-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+               <resource-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+               <resource-match attr="r9c.scheme-authority" match="http://onet.pl" />
+               
+               </condition>
+         </rule>
+
+ </policy>
+
+
+</policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/attr_policy-example8.xml b/tests/ace/test-configuration/attr_policy-example8.xml
new file mode 100644 (file)
index 0000000..c73be53
--- /dev/null
@@ -0,0 +1,55 @@
+<policy-set id="Policy-3" combine="deny-overrides">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject7" func="regexp" />
+        </subject>                                 
+    </target>
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="and">
+                    <condition combine="or">
+                        <subject-match attr="version" match="7" func="equal" />
+                        <subject-match attr="version" match="6" />
+                    </condition>
+                    <resource-match attr="author" match="author2" />
+                </condition>
+            </condition>
+        </rule>
+    </policy>   
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3"  func="regexp"/>
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+    <policy>   
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+ </policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/attre_config.xml b/tests/ace/test-configuration/attre_config.xml
new file mode 100644 (file)
index 0000000..bd52527
--- /dev/null
@@ -0,0 +1,17 @@
+<?xml version="1.0" ?>
+<!DOCTYPE manager-settings SYSTEM "config.dtd">
+<manager-settings>
+  <editable-by-user>false</editable-by-user>
+  <storage-path>/usr/etc/ace/</storage-path>
+  <policy-files>
+    <file active="true">attr_policy-example.xml</file>
+  </policy-files>
+  <trusted-providers>
+    <provider>samsung</provider>
+  </trusted-providers>
+  <untrusted-providers>
+    <provider>nokia</provider>
+  </untrusted-providers>
+</manager-settings>
+
+
diff --git a/tests/ace/test-configuration/general-test.xml b/tests/ace/test-configuration/general-test.xml
new file mode 100644 (file)
index 0000000..c67eaa6
--- /dev/null
@@ -0,0 +1,2621 @@
+<policy-set id="Policy-1" combine="first-matching-target" >      
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject
+            </subject-match>
+        </subject>
+        <subject>
+            <subject-match attr="id" match="subject2" />
+        </subject>
+    </target>
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject" />
+            </subject>
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>
+                <subject-match attr="version" match="3" />
+            </condition>
+        </rule>
+    </policy>        
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject2" />
+            </subject>
+        </target>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>    
+</policy-set>
+<policy-set >
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject3
+            </subject-match>                    
+        </subject>  
+        <subject>
+            <subject-match attr="id" match="subject4" />
+        </subject>                 
+    </target>
+    <policy>             
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                
+            </condition>
+        </rule>
+    </policy>        
+    <policy>            
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy> 
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject4
+                </subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set>    
+<policy-set id="Policy-2" combine="first-matching-target">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject5" />
+        </subject>                 
+        <subject>
+            <subject-match attr="id" match="subject6" />
+        </subject>                 
+    </target>
+    <policy>    
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject5
+                </subject-match>                    
+            </subject>              
+        </target>
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource5
+                </resource-match>                
+                <subject-match attr="version" match="5" />
+            </condition>
+        </rule>
+    </policy> 
+    <policy>             
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="resource-id">
+                    resource6
+                </resource-match>                
+                <subject-match attr="version" match="6" />
+            </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-3" combine="deny-overrides">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject7" />
+        </subject>                                 
+    </target>
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="and">
+                    <condition combine="or">
+                        <subject-match attr="version" match="7" />
+                        <subject-match attr="version" match="6" />
+                    </condition>
+                    <resource-match attr="author" match="author2" />
+                </condition>
+            </condition>
+        </rule>
+    </policy>   
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+    <policy>   
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+ </policy-set>
+
+<policy-set id="Policy-4" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+</policy-set>
+
+<policy-set id="Policy-5" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-6" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8c</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>
+                               <resource-match attr="r8v1" match="1" />
+                               <resource-match attr="r8v2" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+       <policy>
+               <rule effect="deny" />
+       </policy> 
+</policy-set>
+
+<policy-set id="Policy-7" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9a</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable" >
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9a.scheme" match="http" />
+                       </condition>
+        </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>
+                               <resource-match attr="r9a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-8" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9b</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable" >
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b.authority" match="onet.pl:80" />
+                       </condition>
+        </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b" match="777" func="equal" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-9"  combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9c</subject-match>
+        </subject>  
+       </target>
+       <policy combine="permit-overrides" >
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>  
+                               <resource-match attr="r9c.scheme" match="http" />
+                       </condition>
+        </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.authority" match="onet.pl:80" />
+                       </condition>
+        </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.scheme-authority" match="http://onet.pl:80" />
+                       </condition>
+        </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c" match="*" func="glob" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-10" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9d</subject-match>
+        </subject>  
+    </target>
+       <policy combine="first-applicable" >
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d" match="*" func="glob" />
+                       </condition>
+        </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme-authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-11" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9e</subject-match>
+       </subject>  
+    </target>
+       <policy combine="first-applicable" >
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="onet.pl" />
+                       </condition>
+        </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-12" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9f</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable" >
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.scheme-authority" match="http://onet.pl:80" />
+                       </condition>
+        </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-13" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9g</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable" >
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="test.html" />
+                       </condition>
+        </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-14" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9h</subject-match>
+        </subject>  
+       </target>
+       <policy combine="first-applicable" >
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="test.html" />
+                       </condition>
+        </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-15" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-16" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10b</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-17" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10c</subject-match>
+        </subject>  
+    </target>
+       <policy combine="first-applicable" >
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10c2" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10c" match="*" func="glob"/> 
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+
+<!-- justyna -->
+
+<!---    test 13    (old name: test 100)-->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s13</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri.authority" match="buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s16</subject-match>
+                       <subject-match attr="uri.authority" match="v.com.pl"/>
+                       
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 17    (old name: test 104)-->
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s17a</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s17b</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!---    test 18    (old name: test 105)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri" match="buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18b"/>
+                       <subject-match attr="uri" match="buu.s18b.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18c"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="uri" match="buu.s18c.pl"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 19    (old name: test 106)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.1</subject-match>                    
+                 <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.2</subject-match>                    
+                <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+
+<!---    test 20    (old name: test 107)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s20.1</subject-match>                    
+                <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+               <subject-match attr="id">s20.2</subject-match>                    
+               <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!-- justyna -->
+
+
+<!---    test 21    (old name: test 103 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s21</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s21a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="undetermined"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 23    (old name: test 105 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s23</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 24    (old name: test 106 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s24</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <subject-match attr="version" match="5"/>
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.1    (old name: test 107 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <environment-match attr="roaming"  match="off"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.2    (old name: test 107 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.3    (old name: test 107 b U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <subject-match attr="version" match="9"/>                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 25.4    (old name: test 107 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 26.1    (old name: test 108 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.2    (old name: test 108 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.3    (old name: test 108 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 26.4    (old name: test 108 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.1    (old name: test 109 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.2    (old name: test 109a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.3    (old name: test 109b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.3</subject-match>
+                        <subject-match attr="version" match="5"/>                       
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.4    (old name: test 109c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 28    (old name: test 110 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s28</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 29    (old name: test 111 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s29</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.1    (old name: test 112 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.2    (old name: test 112a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.3    (old name: test 112b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.4    (old name: test 112c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+       
+</policy-set>
+
+
+
+<!---    test 31.1    (old name: test 113 U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 31.2.1    (old name: test 113a U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.2.2    (old name: test 113aa U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.3    (old name: test 113b U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.3</subject-match>
+               </subject>  
+       </target>
+
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+</policy-set>
+
+<!---    test 32.1    (old name: test 114 U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 32.2.1    (old name: test 114a U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.2.2    (old name: test 114aa U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.3    (old name: test 114b U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.1    (old name: test 115 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.2    (old name: test 115a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.3    (old name: test 115b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.3</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 34.1    (old name: test 116 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.1</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 34.2    (old name: test 116 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.2</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 35.1    (old name: test 117 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 35.2    (old name: test 117 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set>
+       <target>
+               <subject>
+                       <subject-match attr="id">org.tizen.widget.analogclock</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="http://helloheloo/"/>
+                       </condition>
+                </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 36    (old name: test 102 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s36</subject-match>
+                       <subject-match attr="version" match="5"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+
+<!---    test 37    (old name: test 108 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s37</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-oneshot">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 38    (old name: test 109 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 39    (old name: test 110 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!-- Maria -->
+<!-- testing different methods of policies and rules combining-->
+<!---    test 40    (old name: test 200 -->
+
+<!--- two opposite rules put into different policies in one policy set -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s40</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<!---    test 41    (old name: test 201 -->
+
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s41</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.1    (old name: test 202 -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.2    (old name: test 202b -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 43.1    (old name: test 203 -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+<!---    test 43.2    (old name: test 203b -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.1    (old name: test 204 -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.2    (old name: test 204b -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 45.1    (old name: test 205 -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of permit in contradiction to test 202 -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 45.2    (old name: test 205b -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of deny-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 46.1    (old name: test 206 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 46.2    (old name: test 206b -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 47.1    (old name: test 207 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 47.2    (old name: test 207b -->
+<!--- two opposite rules put into one policy -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 48 (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">s48</subject-match>
+            <subject-match attr="uri.host" match="www.test.pl"/>
+        </subject>
+    </target>
+    <policy>
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id" match="device:pim.contacts"/>
+                <!--<subject-match attr="uri" match="http://www.test.pl:80"/>-->
+            </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<!---    test 51 - BugFest00-->
+
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">BF00</subject-match>
+        </subject>
+    </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id" match="BFR00"/>
+                </condition>
+            </rule>
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="resource-id" match="BFR00"/>
+                </condition>
+            </rule>
+        </policy>
+</policy-set>
+
+
+
+<!---    test 52 - BugFest01-->
+
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">BF01</subject-match>
+        </subject>
+    </target>
+    <policy-set combine="first-matching-target">
+        <policy combine="first-applicable">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id" match="BFR01"/>
+                </condition>
+            </rule>
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="resource-id" match="BFR01"/>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+</policy-set>
+
+
+<!---    test 53 - BugFest02-->
+
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">BF02</subject-match>
+        </subject>
+    </target>
+    <policy-set combine="first-matching-target">
+        <policy combine="permit-overrides">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id" match="BFR02"/>
+                </condition>
+            </rule>
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="resource-id" match="BFR02"/>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+</policy-set>
+
+<!---    test 54 - BugFest03-->
+
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">BF03</subject-match>
+        </subject>
+    </target>
+    <policy-set combine="first-matching-target">
+        <policy combine="deny-overrides">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id" match="BFR03"/>
+                </condition>
+            </rule>
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="resource-id" match="BFR03"/>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+</policy-set>
+
+
+<!---    test 55 - BugFest04-->
+
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">BF04</subject-match>
+        </subject>
+    </target>
+        <policy combine="first-applicable">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id">BFR04</resource-match>
+                </condition>
+            </rule>
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="resource-id">BFR04</resource-match>
+
+                </condition>
+            </rule>
+        </policy>
+</policy-set>
+
+
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">s61a</subject-match>
+        </subject>
+    </target>
+        <policy combine="first-applicable">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id">r61a</resource-match>
+                    <resource-match attr="param:name">type</resource-match>
+                </condition>
+            </rule>
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="resource-id">r61a</resource-match>
+                </condition>
+            </rule>
+        </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">s61b</subject-match>
+        </subject>
+    </target>
+        <policy combine="first-applicable">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id">r61b</resource-match>
+                    <resource-match attr="param:name">type</resource-match>
+                </condition>
+            </rule>
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="resource-id">r61b</resource-match>
+                </condition>
+            </rule>
+        </policy>
+</policy-set>
+
+
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">s61c</subject-match>
+        </subject>
+    </target>
+        <policy combine="first-applicable">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id">r61c</resource-match>
+                    <resource-match attr="param:name">type</resource-match>
+                    <resource-match attr="param:name">port</resource-match>
+                </condition>
+            </rule>
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="resource-id">r61c</resource-match>
+                </condition>
+            </rule>
+        </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">s61d</subject-match>
+        </subject>
+    </target>
+        <policy combine="first-applicable">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id">r61d</resource-match>
+                    <resource-match attr="param:name">type</resource-match>
+                    <resource-match attr="param:name">port</resource-match>
+                </condition>
+            </rule>
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="resource-id">r61d</resource-match>
+                </condition>
+            </rule>
+        </policy>
+</policy-set>
+
+
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">paramTestSubject</subject-match>
+        </subject>
+    </target>
+        <policy combine="first-applicable">
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="dev-cap">messaging</resource-match>
+                    <resource-match attr="param:recipients" func="glob" >+4409*</resource-match>
+                </condition>
+            </rule>
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="dev-cap">messaging</resource-match>
+                    <resource-match attr="param:recipients" func="glob" >+4408*</resource-match>
+                </condition>
+            </rule>
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="dev-cap">messaging</resource-match>
+                    <resource-match attr="param:recipients" func="glob" >+48*</resource-match>
+                </condition>
+            </rule>
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="dev-cap">camera</resource-match>
+                    <resource-match attr="param:quality">high</resource-match>
+                </condition>
+            </rule>
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="dev-cap">camera</resource-match>
+                    <resource-match attr="param:quality">low</resource-match>
+                </condition>
+            </rule>
+        </policy>
+
+</policy-set>
+
+
+</policy-set>
diff --git a/tests/ace/test-configuration/interceptpolicy.xml b/tests/ace/test-configuration/interceptpolicy.xml
new file mode 100644 (file)
index 0000000..ab055ce
--- /dev/null
@@ -0,0 +1,495 @@
+ <policy-set id="Policy-1" combine="first-matching-target">
+
+        <policy-set combine="deny-overrides" >
+            <target>
+                <subject>
+                    <subject-match attr="JilSecurityDomain">
+                        Unidentified
+                    </subject-match>
+                </subject>
+            </target>
+            <policy combine="deny-overrides">
+                <rule effect="deny">
+                    <condition combine="and" >
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/device
+                        </resource-match>
+                        <resource-match attr="param:function">
+                            getAvailableApplications
+                        </resource-match>
+                    </condition>
+                </rule>
+                <rule effect="prompt-oneshot">
+                    <condition combine="or" >
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.update
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.Camera.captureImage
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/device.Device.launchApplication
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            DeviceStateInfo.requestPositionInfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messaging.Messaging.sendMessage
+                        </resource-match>
+                    </condition>
+                </rule>
+                <rule effect="prompt-session">
+                    <condition combine="or" >
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.findAddressBookItems
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.getAddressBookItem
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.getAddressBookItemsCount
+                        </resource-match>
+                    </condition>
+                </rule>
+                <!-- If the resource was not specified above then the access is unrestricted -->
+                <rule effect="permit">
+                    <condition combine="or" >
+                        <resource-match attr="resource-id">
+                            Device.PositionInfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.getAttributeValue
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.getAvailableAttributes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.setAttributeValue
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.open
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.play
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.pause
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.resume
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.stop
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            AudioPlayer.onStateChange
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.Camera.onCameraCaptured
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.Camera.setWindow
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Device.PositionInfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Device.DeviceStateInfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            DeviceStateInfo.onPositionRetrieved
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messaging.Messaging.createMessage
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Messaging.onMessageSendingFailure
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Multimedia.getVolume
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Multimedia.stopAll
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Multimedia.isAudioPlaying
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.createAddressBookItem
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            PIM.onAddressBookItemFound
+                        </resource-match>
+
+                        <!-- This part contains api-features defined in WAC1.0 -->
+
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/accelerometerinfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.5/applicationtypes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.2/camera
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/device
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/devicestateinfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.5/exception
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.5/exceptiontypes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/message
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messagetypes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messaging
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/positioninfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/widget
+                        </resource-match>
+                    </condition>
+                </rule>
+                <rule effect="permit" />
+            </policy>
+        </policy-set>
+
+        <policy-set combine="deny-overrides" >
+            <target>
+                <subject>
+                    <subject-match attr="JilSecurityDomain">
+                        Identified
+                    </subject-match>
+                </subject>
+            </target>
+            <policy combine="deny-overrides">
+                <rule effect="prompt-session">
+                    <condition combine="or" >
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.update
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            DeviceStateInfo.requestPositionInfo
+                        </resource-match>
+                    </condition>
+                </rule>
+                <rule effect="prompt-blanket">
+                    <condition combine="or" >
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/device.Device.launchApplication
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.Camera.captureImage
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messaging.Messaging.sendMessage
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.findAddressBookItems
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.getAddressBookItem
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.getAddressBookItemsCount
+                        </resource-match>
+                    </condition>
+                </rule>
+                <!-- If the resource was not specified above then the access is unrestricted -->
+                <rule effect="permit">
+                    <condition combine="or" >
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/device.Device.getAvailableApplications
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.getAttributeValue
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.getAvailableAttributes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.setAttributeValue
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.open
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.play
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.pause
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.resume
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.stop
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            AudioPlayer.onStateChange
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.Camera.onCameraCaptured
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.Camera.setWindow
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Device.PositionInfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Device.DeviceStateInfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            DeviceStateInfo.onPositionRetrieved
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messaging.Messaging.createMessage
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Messaging.onMessageSendingFailure
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Multimedia.getVolume
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Multimedia.stopAll
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Multimedia.isAudioPlaying
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.createAddressBookItem
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            PIM.onAddressBookItemFound
+                        </resource-match>
+
+                        <!-- This part contains api-features defined in WAC1.0 -->
+
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/accelerometerinfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.5/applicationtypes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.2/camera
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/device
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/devicestateinfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.5/exception
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.5/exceptiontypes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/message
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messagetypes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messaging
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/positioninfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/widget
+                        </resource-match>
+                    </condition>
+                </rule>
+                <rule effect="permit" />
+            </policy>
+        </policy-set>
+
+        <policy-set combine="deny-overrides" >
+            <target>
+                <subject>
+                    <subject-match attr="JilSecurityDomain">
+                        Operator
+                    </subject-match>
+                </subject>
+            </target>
+            <policy combine="deny-overrides">
+                <rule effect="permit">
+                    <condition combine="or" >
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/device.Device.launchApplication
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            DeviceStateInfo.requestPositionInfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.update
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/device.Device.getAvailableApplications
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.getAttributeValue
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.getAvailableAttributes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem.AddressBookItem.setAttributeValue
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.open
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.play
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.pause
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.resume
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.AudioPlayer.stop
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            AudioPlayer.onStateChange
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.Camera.onCameraCaptured
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.Camera.setWindow
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia.Camera.captureImage
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Device.PositionInfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Device.DeviceStateInfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            DeviceStateInfo.onPositionRetrieved
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messaging.Messaging.createMessage
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messaging.Messaging.sendMessage
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Messaging.onMessageSendingFailure
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Multimedia.getVolume
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Multimedia.stopAll
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            Multimedia.isAudioPlaying
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.createAddressBookItem
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            PIM.onAddressBookItemFound
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.findAddressBookItems
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.getAddressBookItem
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim.PIM.getAddressBookItemsCount
+                        </resource-match>
+
+                        <!-- This part contains api-features defined in WAC1.0 -->
+
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/accelerometerinfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/addressbookitem
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.5/applicationtypes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.2/camera
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/device
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/devicestateinfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.5/exception
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.5/exceptiontypes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/message
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messagetypes
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/messaging
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/multimedia
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1.1/pim
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/positioninfo
+                        </resource-match>
+                        <resource-match attr="resource-id">
+                            http://jil.org/jil/api/1.1/widget
+                        </resource-match>
+                    </condition>
+                </rule>
+                <rule effect="permit" />
+            </policy>
+        </policy-set>
+ </policy-set>
diff --git a/tests/ace/test-configuration/old_policy-example.xml b/tests/ace/test-configuration/old_policy-example.xml
new file mode 100644 (file)
index 0000000..d7ce388
--- /dev/null
@@ -0,0 +1,50 @@
+ <policy-set id="Policy-1" combine="first-matching-target">
+    
+    <policy>
+          <target>
+             <subject>
+                 <subject-match attr="name" match="analogclock"/>               
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="resource-id">
+                     device.simcard 
+                 </resource-match>
+             </condition>
+         </rule>
+     </policy>        
+     
+     <policy>
+         <target>
+             <subject>
+                 <subject-match attr="name" match="memo" />             
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="resource-id">
+                    file.write 
+                 </resource-match>
+                 <subject-match attr="name" match="memo" />
+             </condition>
+         </rule>
+     </policy>   
+   
+     <policy>
+         <target>
+             <subject>
+                 <subject-match attr="name" match="phonesearch" />              
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="resource-id">
+                     pim.contact 
+                 </resource-match>
+                 <subject-match attr="name" match="phonesearch" />
+             </condition>
+         </rule>
+     </policy> 
+
+ </policy-set>
diff --git a/tests/ace/test-configuration/policy-example.xml b/tests/ace/test-configuration/policy-example.xml
new file mode 100644 (file)
index 0000000..c0e0857
--- /dev/null
@@ -0,0 +1,95 @@
+ <policy-set id="Policy-1" combine="first-matching-target">
+     <!---
+     <policy>
+         <rule effect="permit"/>
+     </policy>
+     -->
+    <policy>
+          <target>
+             <subject>
+                 <subject-match attr="name" match="analogclock"/>               
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="api-feature">
+                     devicestatus 
+                 </resource-match>
+                 <!--
+                 <resource-match attr="feature-install-uri">
+                    ww.samsung.com1
+                 </resource-match>
+                 -->
+             </condition>
+         </rule>
+     </policy>        
+     
+    <policy>
+          <target>
+             <subject>
+                 <subject-match attr="name" match="batteryMonitor"/>            
+             </subject>
+         </target>
+         <rule effect="permit">
+          <condition>
+                 <resource-match attr="api-feature">
+                     devicestatus 
+                 </resource-match>
+             </condition>
+         </rule>
+     </policy>        
+    
+    <policy>
+          <target>
+             <subject>
+                 <subject-match attr="name" match="appconfig"/>                 
+             </subject>
+         </target>
+         <rule effect="deny">
+             <condition>
+                 <resource-match attr="api-feature">
+                     http://bondi.omtp.org/api.appconfig 
+                 </resource-match>
+             </condition>
+         </rule>
+     </policy>        
+    
+    
+     <policy>
+         <rule effect="permit"/>
+     </policy>
+     
+     
+     <policy>
+         <target>
+             <subject>
+                 <subject-match attr="name" match="memo" />             
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="resource-id">
+                    file.write 
+                 </resource-match>
+                 <subject-match attr="name" match="memo" />
+             </condition>
+         </rule>
+     </policy>   
+   
+     <policy>
+         <target>
+             <subject>
+                 <subject-match attr="name" match="phonesearch" />              
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="resource-id">
+                     pim.contact 
+                 </resource-match>
+                 <subject-match attr="name" match="phonesearch" />
+             </condition>
+         </rule>
+     </policy> 
+
+ </policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/policy-example2.xml b/tests/ace/test-configuration/policy-example2.xml
new file mode 100644 (file)
index 0000000..dded65c
--- /dev/null
@@ -0,0 +1,50 @@
+ <policy-set id="Policy-1" combine="first-matching-target">
+    
+    <policy>
+          <target>
+             <subject>
+                 <subject-match attr="name" match="analogclock" />              
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="resource-id">
+                     device.simcard 
+                 </resource-match>
+             </condition>
+         </rule>
+     </policy>        
+     
+     <policy>
+         <target>
+             <subject>
+                 <subject-match attr="name" match="memo" />             
+             </subject>
+         </target>
+         <rule effect="deny">
+             <condition>
+                 <resource-match attr="resource-id">
+                      file.write
+                 </resource-match>
+                 <subject-match attr="name" match="memo" />
+             </condition>
+         </rule>
+     </policy>   
+   
+     <policy>
+         <target>
+             <subject>
+                 <subject-match attr="name" match="phonesearch" />              
+             </subject>
+         </target>
+         <rule effect="prompt-oneshot">
+             <condition>
+                 <resource-match attr="resource-id">
+                     pim.contact 
+                 </resource-match>
+                 <subject-match attr="name" match="phonesearch" />
+             </condition>
+         </rule>
+     </policy> 
+
+ </policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/policy-example3.xml b/tests/ace/test-configuration/policy-example3.xml
new file mode 100644 (file)
index 0000000..ef0fddc
--- /dev/null
@@ -0,0 +1,50 @@
+ <policy-set id="Policy-1" combine="first-matching-target">
+    
+    <policy>
+          <target>
+             <subject>
+                 <subject-match attr="name" match="analogclock" />              
+             </subject>
+         </target>
+         <rule effect="prompt-blanket">
+             <condition>
+                 <resource-match attr="resource-id">
+                     device.simcard 
+                 </resource-match>
+             </condition>
+         </rule>
+     </policy>        
+     
+     <policy>
+         <target>
+             <subject>
+                 <subject-match attr="name" match="memo" />             
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="resource-id">
+                      file.write
+                 </resource-match>
+                 <subject-match attr="name" match="memo" />
+             </condition>
+         </rule>
+     </policy>   
+   
+     <policy>
+         <target>
+             <subject>
+                 <subject-match attr="name" match="phonesearch" />              
+             </subject>
+         </target>
+         <rule effect="permit">
+             <condition>
+                 <resource-match attr="resource-id">
+                     pim.contact 
+                 </resource-match>
+                 <subject-match attr="name" match="phonesearch" />
+             </condition>
+         </rule>
+     </policy> 
+
+ </policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/policy-test-gsettings.xml b/tests/ace/test-configuration/policy-test-gsettings.xml
new file mode 100644 (file)
index 0000000..2a242f6
--- /dev/null
@@ -0,0 +1,41 @@
+<policy-set id="Policy-4" combine="first-matching-target">
+<policy>
+       <target>
+               <subject>
+                       <subject-match attr="id">a1</subject-match>
+               </subject>  
+       </target>
+       
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">d3</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+<policy>
+       <target>
+               <subject>
+                       <subject-match attr="id">aa2</subject-match>
+               </subject>  
+       </target>
+       
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">bb2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+
+<policy>
+       <target>
+               <subject>
+                       <subject-match attr="id">c3</subject-match>
+               </subject>  
+       </target>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">d3</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/policy-test.xml b/tests/ace/test-configuration/policy-test.xml
new file mode 100644 (file)
index 0000000..9094ee4
--- /dev/null
@@ -0,0 +1,41 @@
+<policy-set id="Policy-4" combine="first-matching-target">
+<policy>
+       <target>
+               <subject>
+                       <subject-match attr="id">a1</subject-match>
+               </subject>  
+       </target>
+       
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">b1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+<policy>
+       <target>
+               <subject>
+                       <subject-match attr="id">aa2</subject-match>
+               </subject>  
+       </target>
+       
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">bb2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+
+<policy>
+       <target>
+               <subject>
+                       <subject-match attr="id">c3</subject-match>
+               </subject>  
+       </target>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">d3</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/policy-wac-2.0.xml b/tests/ace/test-configuration/policy-wac-2.0.xml
new file mode 100644 (file)
index 0000000..cf59001
--- /dev/null
@@ -0,0 +1,103 @@
+<policy-set id="Policy-1" combine="first-matching-target">
+ <policy description="WAC">
+
+     <!-- permit access to private filesystem -->
+     <rule effect="permit">
+         <condition>
+             <resource-match attr="device-cap" match="messaging.write"/>
+         </condition>
+     </rule>
+     <!-- permit access to camera preview -->
+     <rule effect="permit">
+         <condition>
+             <resource-match attr="device-cap" match="camera.show"/>
+         </condition>
+
+     </rule>
+     <!-- prompt-blanket access to IMEI -->
+     <rule effect="prompt-blanket">
+         <condition>
+             <resource-match attr="device-cap" match="devicestatus.networkinfo"/>
+             <resource-match attr="param:property" match="imei"/>
+         </condition>
+     </rule>
+     <!-- prompt-session access to messging when roaming -->
+     <rule effect="prompt-session">
+         <condition>
+             <resource-match attr="device-cap" match="messaging.send"/>
+             <environment-match attr="roaming" match="true"/>
+         </condition>
+     </rule>
+     <!-- prompt-session access to network when roaming -->
+     <rule effect="prompt-session">
+         <condition>
+             <condition combine="or">
+                 <resource-match attr="device-cap" match="XMLHttpRequest"/>
+                 <resource-match attr="device-cap" match="externalNetworkAccess"/>
+             </condition>
+             <environment-match attr="roaming" match="true"/>
+         </condition>
+     </rule>
+     <!-- prompt-blanket access to camera capture -->
+     <rule effect="prompt-blanket">
+         <condition>
+             <resource-match attr="device-cap" match="camera.capture"/>
+         </condition>
+     </rule>
+     <!-- prompt-blanket access to contacts -->
+     <rule effect="prompt-blanket">
+         <condition>
+             <resource-match attr="device-cap" match="pim.contact.*"/>
+         </condition>
+     </rule>
+     <!-- prompt-blanket access to calendar -->
+     <rule effect="prompt-blanket">
+         <condition>
+             <resource-match attr="device-cap" match="pim.calendar.*"/>
+         </condition>
+     </rule>
+     <!-- prompt-blanket access to task -->
+     <rule effect="prompt-blanket">
+         <condition>
+             <resource-match attr="device-cap" match="pim.task.*"/>
+         </condition>
+     </rule>
+     <!-- prompt-blanket access to devicestatus -->
+     <rule effect="prompt-blanket">
+         <condition>
+             <resource-match attr="device-cap" match="devicestatus.*"/>
+         </condition>
+     </rule>
+     <!-- prompt-blanket access to geolocation -->
+     <rule effect="prompt-oneshot">
+         <condition>
+             <resource-match attr="device-cap" match="geolocation"/>
+         </condition>
+     </rule>
+     <!-- prompt-blanket access to networking -->
+     <rule effect="prompt-session">
+         <condition combine="or">
+             <resource-match attr="device-cap" match="XMLHttpRequest"/>
+             <resource-match attr="device-cap" match="externalNetworkAccess"/>
+         </condition>
+     </rule>
+     <!-- prompt-blanket access to filesystem -->
+     <rule effect="prompt-blanket">
+         <condition>
+             <resource-match attr="device-cap" match="filesystem.*"/>
+         </condition>
+     </rule>
+     <rule effect="deny">
+         <condition>
+             <resource-match attr="device-cap" match="messaging.subscribe"/>
+         </condition>
+     </rule>
+     <!-- permit access to all remaining deviceapis -->
+     <rule effect="permit">
+         <condition>
+             <resource-match attr="device-cap" match="*"/>
+         </condition>
+     </rule>
+     <rule effect="permit"/>
+</policy>
+</policy-set>
diff --git a/tests/ace/test-configuration/policy_example.xml b/tests/ace/test-configuration/policy_example.xml
new file mode 100644 (file)
index 0000000..333422d
--- /dev/null
@@ -0,0 +1,2407 @@
+<policy-set id="Policy-1">      
+<policy-set combine="first-matching-target">
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject
+            </subject-match>
+        </subject>
+        <subject>
+            <subject-match attr="id" match="subject2" />
+        </subject>
+    </target>
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject" />
+            </subject>
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>
+                <subject-match attr="version" match="3" />
+            </condition>
+        </rule>
+    </policy>        
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id" match="subject2" />
+            </subject>
+        </target>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>    
+</policy-set>
+<policy-set >
+    <target>
+        <subject>
+            <subject-match attr="id">
+                subject3
+            </subject-match>                    
+        </subject>  
+        <subject>
+            <subject-match attr="id" match="subject4" />
+        </subject>                 
+    </target>
+    <policy>             
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                
+            </condition>
+        </rule>
+    </policy>        
+    <policy>            
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource2
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy> 
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject4
+                </subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set>    
+<policy-set id="Policy-2" combine="first-matching-target">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject5" />
+        </subject>                 
+        <subject>
+            <subject-match attr="id" match="subject6" />
+        </subject>                 
+    </target>
+    <policy>    
+        <target>
+            <subject>
+                <subject-match attr="id">
+                    subject5
+                </subject-match>                    
+            </subject>              
+        </target>
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource5
+                </resource-match>                
+                <subject-match attr="version" match="5" />
+            </condition>
+        </rule>
+    </policy> 
+    <policy>             
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="resource-id">
+                    resource6
+                </resource-match>                
+                <subject-match attr="version" match="6" />
+            </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-3" combine="deny-overrides">
+    <target>      
+        <subject>
+            <subject-match attr="id" match="subject7" />
+        </subject>                                 
+    </target>
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="and">
+                    <condition combine="or">
+                        <subject-match attr="version" match="7" />
+                        <subject-match attr="version" match="6" />
+                    </condition>
+                    <resource-match attr="author" match="author2" />
+                </condition>
+            </condition>
+        </rule>
+    </policy>   
+    <policy>   
+        <rule effect="permit">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+    <policy>   
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="resource-id">
+                    resource7
+                </resource-match>    
+                <condition combine="or">
+                    <condition combine="or">
+                        <subject-match attr="version" match="1" />
+                        <subject-match attr="version" match="2" />
+                    </condition>
+                    <resource-match attr="author" match="author3" />
+                </condition>
+            </condition>
+        </rule>
+    </policy> 
+ </policy-set>
+
+<policy-set id="Policy-4" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+</policy-set>
+
+<policy-set id="Policy-5" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v2" match="2" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>    
+                               <resource-match attr="r8v1" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-6" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s8c</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r8</resource-match>
+                               <resource-match attr="r8v1" match="1" />
+                               <resource-match attr="r8v2" match="1" />
+                       </condition>
+        </rule>
+    </policy>
+       <policy>
+               <rule effect="deny" />
+       </policy> 
+</policy-set>
+
+<policy-set id="Policy-7" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9a.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>
+                               <resource-match attr="r9a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-8" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9b</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9b" match="777" func="equal" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-9"  combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9c</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>  
+                               <resource-match attr="r9c.scheme" match="http" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.authority" match="onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c.scheme-authority" match="http://onet.pl" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9c" match="*" func="glob" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-10" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9d</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d" match="*" func="glob" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9d.scheme-authority" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-11" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9e</subject-match>
+       </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-12" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9f</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e.host" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9e" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-13" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9g</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set  id="Policy-14" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s9h</subject-match>
+        </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g.path" match="http://onet.pl:80/test.html" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r9</resource-match>    
+                               <resource-match attr="r9g" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-15" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10a</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<policy-set id="Policy-16" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10b</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10a" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10a" match="*" func="glob"/>
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+<policy-set id="Policy-17" combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s10c</subject-match>
+        </subject>  
+    </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>    
+                               <resource-match attr="r10c" match="[1234567890]+[ab]+" func="regexp" />
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r10</resource-match>
+                               <resource-match attr="r10c" match="*" func="glob"/> 
+                       </condition>
+        </rule>
+    </policy>  
+</policy-set>
+
+
+<!-- justyna -->
+
+<!---    test 13    (old name: test 100)-->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s13</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 14    (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s14</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 15    (old name: test 102) -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri.host" match="//buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 16    (old name: test 103) -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s16</subject-match>
+                       <subject-match attr="uri.host" match="v.com.pl"/>
+                       
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 17    (old name: test 104)-->
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject4</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">subject5</subject-match>                    
+                <subject-match attr="version" match="4" />
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!---    test 18    (old name: test 105)-->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="uri" match="buu.com.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18b"/>
+                       <subject-match attr="uri" match="buu.s18b.pl"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id" match="s18c"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="uri" match="buu.s18c.pl"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 19    (old name: test 106)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.1</subject-match>                    
+                 <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s19.2</subject-match>                    
+                <subject-match attr="key-root-trust" match="voperator"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+
+
+<!---    test 20    (old name: test 107)-->
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s20.1</subject-match>                    
+                <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<policy-set combine="first-matching-target">
+        <target>
+            <subject>
+               <subject-match attr="id">s20.2</subject-match>                    
+               <subject-match attr="signer-id" match="v7zha89%49x£$"/>
+            </subject>  
+        </target>
+<policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="resource-id">
+                    resource4
+                </resource-match>                    
+            </condition>
+        </rule>
+    </policy>
+</policy-set> 
+
+<!-- justyna -->
+
+
+<!---    test 21    (old name: test 103 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s21</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 23    (old name: test 105 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s23</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 24    (old name: test 106 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s24</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <subject-match attr="version" match="5"/>
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.1    (old name: test 107 U)-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.2    (old name: test 107 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 25.3    (old name: test 107 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 25.4    (old name: test 107 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s25.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       
+                       
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 26.1    (old name: test 108 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.2    (old name: test 108 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 26.3    (old name: test 108 b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 26.4    (old name: test 108 c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s26.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>                    
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.1    (old name: test 109 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.2    (old name: test 109a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 27.3    (old name: test 109b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 27.4    (old name: test 109c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s27.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 28    (old name: test 110 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s28</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 29    (old name: test 111 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s29</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.1    (old name: test 112 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.2    (old name: test 112a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 30.3    (old name: test 112b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 30.4    (old name: test 112c U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s30.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       
+               </condition>
+                        </rule>
+       </policy>
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+       
+</policy-set>
+
+
+
+<!---    test 31.1    (old name: test 113 U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 31.2.1    (old name: test 113a U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.2.2    (old name: test 113aa U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 31.3    (old name: test 113b U -->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s31.3</subject-match>
+               </subject>  
+       </target>
+
+       
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+</policy-set>
+
+<!---    test 32.1    (old name: test 114 U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 32.2.1    (old name: test 114a U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.2.2    (old name: test 114aa U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.2.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 32.3    (old name: test 114b U -->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s32.3</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+               <condition combine="or">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+
+       <policy>
+               <rule effect="deny">
+               <condition combine="and">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.1    (old name: test 115 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.2    (old name: test 115a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 33.3    (old name: test 115b U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s33.3</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="or">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 34.1    (old name: test 116 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.1</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 34.2    (old name: test 116 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s34.2</subject-match>
+               </subject>  
+       </target>
+       <policy  combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>               
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+<!---    test 35.1    (old name: test 117 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 35.2    (old name: test 117 a U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s35.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device"/>
+                               <subject-match attr="version" match="5"/>
+                               
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set>
+       <target>
+               <subject>
+                       <subject-match attr="id">org.tizen.widget.analogclock</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="http://helloheloo/"/>
+                       </condition>
+                </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 36    (old name: test 102 U -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s36</subject-match>
+                       <subject-match attr="version" match="5"/>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                               <subject-match attr="version" match="5"/>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+
+
+<!---    test 37    (old name: test 108 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s37</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-oneshot">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 38    (old name: test 109 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s38.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-session">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<!---    test 39    (old name: test 110 -->
+<!-- mbialota modified -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s39.4</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="prompt-blanket">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">device:pim.contacts.read</resource-match>
+                       </condition>
+                        </rule>
+       </policy>
+</policy-set>
+
+
+<!-- Maria -->
+<!-- testing different methods of policies and rules combining-->
+<!---    test 40    (old name: test 200 -->
+
+<!--- two opposite rules put into different policies in one policy set -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s40</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r40</resource-match>    
+                       </condition>
+        </rule>
+    </policy>
+</policy-set>
+
+<!---    test 41    (old name: test 201 -->
+
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s41</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r41.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.1    (old name: test 202 -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 42.2    (old name: test 202b -->
+<!--- two opposite rules put into one policy in one policy set-->
+<!--- this case will have the result of deny because of default rules combining==deny override, which is not the same as policies combining -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s42.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r42.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 43.1    (old name: test 203 -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+<!---    test 43.2    (old name: test 203b -->
+
+<!--- two opposite rules put into different policies in one policy set-->
+<policy-set combine="deny-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s43.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r43.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.1    (old name: test 204 -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.1</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.1</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 44.2    (old name: test 204b -->
+<!--- two different rules put into different policies in one policy set-->
+<policy-set combine="permit-overrides">
+       <target>
+               <subject>
+                       <subject-match attr="id">s44.2</subject-match>
+               </subject>  
+       </target>
+       <policy>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+       <policy>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r44.2</resource-match>    
+                       </condition>
+               </rule>
+    </policy>
+</policy-set>
+
+<!---    test 45.1    (old name: test 205 -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of permit in contradiction to test 202 -->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 45.2    (old name: test 205b -->
+<!--- two opposite rules put into one policy -->
+<!--- testing rules combining methods-->
+<!--- this case should have the result of deny-->
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s45.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="first-applicable">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r45.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 46.1    (old name: test 206 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 46.2    (old name: test 206b -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s46.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="permit-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r46.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+<!---    test 47.1    (old name: test 207 -->
+<!--- two opposite rules put into one policy -->
+
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.1</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.1</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+<!---    test 47.2    (old name: test 207b -->
+<!--- two opposite rules put into one policy -->
+
+<policy-set combine="first-matching-target">
+       <target>
+               <subject>
+                       <subject-match attr="id">s47.2</subject-match>
+               </subject>  
+       </target>
+       <policy combine="deny-overrides">
+               <rule effect="deny">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+               <rule effect="permit">
+                       <condition combine="and">
+                               <resource-match attr="resource-id">r47.2</resource-match>    
+                       </condition>
+               </rule>
+       </policy>
+</policy-set>
+
+
+<!---    test 48 (old name: test 101)-->
+
+<policy-set combine="first-matching-target">
+<target>
+<subject>
+<subject-match attr="id">s48</subject-match>
+<subject-match attr="uri.host" match="www.test.pl"/>
+
+</subject>
+</target>
+<policy>
+<rule effect="permit">
+<condition combine="and">
+<resource-match attr="resource-id" match="device:pim.contacts"/>
+<!--<subject-match attr="uri" match="http://www.test.pl:80"/>-->
+</condition>
+</rule>
+</policy>
+</policy-set>
+
+</policy-set>
diff --git a/tests/ace/test-configuration/reproduce-abort-test.xml b/tests/ace/test-configuration/reproduce-abort-test.xml
new file mode 100644 (file)
index 0000000..ee2de20
--- /dev/null
@@ -0,0 +1,26 @@
+<policy-set id="Policy-1">      
+
+<policy>                                                            
+     <target>
+<!--                                                     
+         <subject>                                                 
+             <subject-match attr="id" match="analogclock"/>      
+         </subject>
+-->                                                
+     </target>                                                
+     <rule effect="permit">                                  
+         <condition>                                          
+       <!--
+             <resource-match attr="resource-id">              
+                  api.appconfig                               
+             </resource-match>                               
+             <resource-match attr="device-cap">              
+                  api.appconfig                               
+             </resource-match>                               
+       -->
+         </condition>                                        
+     </rule>                                                 
+</policy>   
+
+
+</policy-set>
\ No newline at end of file
diff --git a/tests/ace/test-configuration/undefined-test.xml b/tests/ace/test-configuration/undefined-test.xml
new file mode 100644 (file)
index 0000000..3da1b1c
--- /dev/null
@@ -0,0 +1,1075 @@
+<policy-set combine="deny-overrides" >
+    <policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s25.2</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s25.3</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <subject-match attr="version" match="9"/>
+                    </condition>
+
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+    <!---    test 25.4    (old name: test 107 c U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s25.4</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+
+
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+
+    <!---    test 26.1    (old name: test 108 U -->
+    <policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s26.1</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 26.2    (old name: test 108 a U -->
+    <policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s26.2</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 26.3    (old name: test 108 b U -->
+    <policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s26.3</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+    <!---    test 26.4    (old name: test 108 c U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s26.4</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+
+    <!---    test 27.1    (old name: test 109 U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s27.1</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+    <!---    test 27.2    (old name: test 109a U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s27.2</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+    <!---    test 27.3    (old name: test 109b U -->
+    <policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s27.3</subject-match>
+                <subject-match attr="version" match="5"/>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+
+    <!---    test 27.4    (old name: test 109c U -->
+    <policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s27.4</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+
+    <!---    test 28    (old name: test 110 U -->
+    <policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s28</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 29    (old name: test 111 U -->
+    <policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s29</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+    <!---    test 30.1    (old name: test 112 U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s30.1</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="deny">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 30.2    (old name: test 112a U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s30.2</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="deny">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 30.3    (old name: test 112b U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s30.3</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="deny">
+                <condition combine="and">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+    <!---    test 30.4    (old name: test 112c U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s30.4</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="deny">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+    </policy-set>
+
+
+
+    <!---    test 31.1    (old name: test 113 U -->
+    <policy-set combine="deny-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s31.1</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="deny">
+                <condition combine="and">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+
+    <!---    test 31.2.1    (old name: test 113a U -->
+    <policy-set combine="deny-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s31.2.1</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="deny">
+                <condition combine="or">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 31.2.2    (old name: test 113aa U -->
+    <policy-set combine="deny-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s31.2.2</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 31.3    (old name: test 113b U -->
+    <policy-set combine="deny-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s31.3</subject-match>
+            </subject>
+        </target>
+
+
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+    </policy-set>
+
+    <!---    test 32.1    (old name: test 114 U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s32.1</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="deny">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 32.2.1    (old name: test 114a U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s32.2.1</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="deny">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+    <!---    test 32.2.2    (old name: test 114aa U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s32.2.2</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="deny">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="deny">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+    <!---    test 32.3    (old name: test 114b U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s32.3</subject-match>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="deny">
+                <condition combine="or">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="or">
+                        <resource-match attr="resource-id"  match="device"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+
+        <policy>
+            <rule effect="deny">
+                <condition combine="and">
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                    <condition combine="and">
+                        <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                        <subject-match attr="version" match="5"/>
+
+                    </condition>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 33.1    (old name: test 115 U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s33.1</subject-match>
+            </subject>
+        </target>
+        <policy combine="first-applicable">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 33.2    (old name: test 115a U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s33.2</subject-match>
+            </subject>
+        </target>
+        <policy combine="first-applicable">
+            <rule effect="permit">
+                <condition combine="or">
+                    <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 33.3    (old name: test 115b U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s33.3</subject-match>
+            </subject>
+        </target>
+        <policy combine="first-applicable">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+            <rule effect="permit">
+                <condition combine="or">
+                    <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 34.1    (old name: test 116 U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s34.1</subject-match>
+            </subject>
+        </target>
+        <policy  combine="permit-overrides">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim"/>
+                    <subject-match attr="version" match="5"/>
+                </condition>
+            </rule>
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+    <!---    test 34.2    (old name: test 116 a U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s34.2</subject-match>
+            </subject>
+        </target>
+        <policy  combine="permit-overrides">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                    <subject-match attr="version" match="5"/>
+                </condition>
+            </rule>
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+
+    <!---    test 35.1    (old name: test 117 U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s35.1</subject-match>
+            </subject>
+        </target>
+        <policy combine="deny-overrides">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 35.2    (old name: test 117 a U -->
+    <policy-set combine="permit-overrides">
+        <target>
+            <subject>
+                <subject-match attr="id">s35.2</subject-match>
+            </subject>
+        </target>
+        <policy combine="deny-overrides">
+            <rule effect="deny">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device"/>
+                    <subject-match attr="version" match="5"/>
+
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+    <policy-set>
+        <target>
+            <subject>
+                <subject-match attr="id">org.tizen.widget.analogclock</subject-match>
+            </subject>
+        </target>
+        <policy combine="first-applicable">
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="http://helloheloo/"/>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+
+    <!---    test 36    (old name: test 102 U -->
+    <policy-set combine="first-matching-target">
+        <target>
+            <subject>
+                <subject-match attr="id">s36</subject-match>
+                <subject-match attr="version" match="5"/>
+            </subject>
+        </target>
+        <policy>
+            <rule effect="permit">
+                <condition combine="and">
+                    <resource-match attr="resource-id"  match="device:pim.contacts"/>
+                    <subject-match attr="version" match="5"/>
+                </condition>
+            </rule>
+        </policy>
+    </policy-set>
+
+</policy-set>
diff --git a/tests/ace/widget_installer.h b/tests/ace/widget_installer.h
new file mode 100644 (file)
index 0000000..71e77c7
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    widget_installer.h
+ * @author  Tomasz Swierczek (t.swierczek@samsung.com)
+ * @brief   Class that manages widget installation for ACE tests
+ */
+#ifndef _TESTS_ACE_WIDGET_INSTALLER_H_
+#define _TESTS_ACE_WIDGET_INSTALLER_H_
+
+#include <ace-dao-rw/AceDAO.h>
+#include <ace-dao-ro/common_dao_types.h>
+#include <sys/time.h>
+#include <ctime>
+#include <cstdlib>
+
+#define INVALID_WIDGET_HANDLE -1
+
+using namespace AceDB;
+
+namespace InstallerMockup {
+
+class WacSecurityMock : public IWacSecurity
+{
+public:
+    WacSecurityMock() :
+        mRecognized(false),
+        mDistributorSigned(false),
+        mWacSigned(false)
+    {
+    }
+
+    virtual const WidgetCertificateDataList& getCertificateList() const
+    {
+        return mList;
+    }
+
+    virtual bool isRecognized() const { return mRecognized; }
+    virtual bool isDistributorSigned() const { return mDistributorSigned; }
+    virtual bool isWacSigned() const { return mWacSigned; }
+    virtual void getCertificateChainList(CertificateChainList& /*lst*/) const {}
+    virtual void getCertificateChainList(CertificateChainList&,
+            CertificateSource) const {}
+
+    WidgetCertificateDataList& getCertificateListRef()
+    {
+        return mList;
+    }
+
+    void setRecognized(bool recognized) { mRecognized = recognized; }
+    void setDistributorSigned(bool distributorSigned)
+    {
+        mDistributorSigned = distributorSigned;
+    }
+    void setWacSigned(bool wacSigned) { mWacSigned = wacSigned; }
+
+private:
+    WidgetCertificateDataList mList;
+    // author signature verified
+    bool mRecognized;
+    // known distribuor
+    bool mDistributorSigned;
+    // distributor is wac
+    bool mWacSigned;
+
+};
+
+static WidgetHandle _registerWidget(const WidgetRegisterInfo& regInfo,
+                                    const IWacSecurity& sec,
+                                    int line)
+{
+    //randomize widget handle
+    WidgetHandle handle = INVALID_WIDGET_HANDLE;
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    srand(time(NULL) + tv.tv_usec);
+    do {
+        handle = rand();
+    } while (AceDAOReadOnly::isWidgetInstalled(handle));
+
+    try
+    {
+        auto previous = AceDAOReadOnly::getHandleList();
+
+        // register widget
+        AceDAO::registerWidgetInfo(handle, regInfo, sec.getCertificateList());
+
+        RUNNER_ASSERT_MSG(handle != INVALID_WIDGET_HANDLE,
+                          "(called from line " << line << ")");
+
+        auto current = AceDAOReadOnly::getHandleList();
+        RUNNER_ASSERT_MSG(previous.size()+1 == current.size(),
+                          "(called from line " << line << ")");
+
+        RUNNER_ASSERT_MSG(AceDAOReadOnly::isWidgetInstalled(handle),
+                          "(called from line " << line << ")");
+    } catch (AceDAOReadOnly::Exception::DatabaseError) {
+        RUNNER_ASSERT_MSG(
+                false,
+                "Unexpected exception (called from line " << line << ")");
+    }
+    return handle;
+}
+
+WidgetHandle registerWidget(AppTypes appType = AppTypes::WAC20)
+{
+    WacSecurityMock sec;
+    WidgetRegisterInfo regInfo;
+    regInfo.type = appType;
+    return _registerWidget(regInfo, sec, __LINE__);
+}
+
+} // namespace
+
+#endif // _TESTS_ACE_WIDGET_INSTALLER_H_
diff --git a/tests/ace_client/CMakeLists.txt b/tests/ace_client/CMakeLists.txt
new file mode 100644 (file)
index 0000000..74f0701
--- /dev/null
@@ -0,0 +1,80 @@
+#
+#Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an "AS IS" BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @version     0.1
+#
+include(FindPkgConfig)
+
+SET(TARGET_ACE_CLIENT_TEST "wrt-tests-ace-client")
+
+PKG_CHECK_MODULES(ACE_CLIENT_TEST_DEPS
+    dpl-test-efl
+    dpl-db-efl
+    REQUIRED
+    )
+
+SET(ACE_CLIENT_TEST_SOURCES
+    ${COMMUNICATION_CLIENT_SOURCES}
+    ${PROJECT_SOURCE_DIR}/tests/ace_client/ace_client_tests.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace_client/test_cases.cpp
+    ${PROJECT_SOURCE_DIR}/ace_client/src/ace_client.cpp
+    ${PROJECT_SOURCE_DIR}/ace_client/src/ace_api_client.cpp
+    ${PROJECT_SOURCE_DIR}/ace/engine/Attribute.cpp
+    ${PROJECT_SOURCE_DIR}/ace/engine/Policy.cpp
+    ${PROJECT_SOURCE_DIR}/ace/engine/Rule.cpp
+    ${PROJECT_SOURCE_DIR}/ace/engine/Condition.cpp
+    ${PROJECT_SOURCE_DIR}/ace/engine/Subject.cpp
+    ${PROJECT_SOURCE_DIR}/ace/engine/TreeNode.cpp
+    ${PROJECT_SOURCE_DIR}/ace/dao/BaseAttribute.cpp
+    ${PROJECT_SOURCE_DIR}/src/services/ace/logic/attribute_facade.cpp
+    ${PROJECT_SOURCE_DIR}/src/services/ace/logic/simple_roaming_agent.cpp
+    ${PROJECT_SOURCE_DIR}/mockups/AceDAOReadOnly_mock.cpp
+    ${PROJECT_SOURCE_DIR}/mockups/communication_client_mock.cpp
+    )
+
+SET(ACE_CLIENT_TEST_INCLUDES
+    ${COMMUNICATION_CLIENT_INCLUDES}
+    ${ACE_CLIENT_DEPS_INCLUDE_DIRS}
+    ${PROJECT_SOURCE_DIR}/ace_client/include
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    ${PROJECT_SOURCE_DIR}/ace_client/include/ace-client
+    ${PROJECT_SOURCE_DIR}/ace/include/
+    ${PROJECT_SOURCE_DIR}/ace/include/ace/
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/
+    ${PROJECT_SOURCE_DIR}/mockups/                     # Mockups
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus/             # Security daemon config
+    ${PROJECT_SOURCE_DIR}/src/services/ace/            # AceServerApi
+    ${PROJECT_SOURCE_DIR}/src/services/ace/dbus/api/
+    ${PROJECT_SOURCE_DIR}/src/services/popup/dbus/api/ # PopupResponseServerApi
+    ${PROJECT_SOURCE_DIR}/src/services/popup
+    ${PROJECT_SOURCE_DIR}/src/services/ace/logic/
+    )
+
+ADD_DEFINITIONS(${ACE_CLIENT_TEST_DEPS_CFLAGS})
+ADD_DEFINITIONS(${ACE_CLIENT_TEST_CFLAGS_OTHER})
+ADD_DEFINITIONS(-D ACE_CLIENT_TESTS)
+
+INCLUDE_DIRECTORIES(${ACE_CLIENT_TEST_INCLUDES})
+
+ADD_EXECUTABLE(${TARGET_ACE_CLIENT_TEST} ${ACE_CLIENT_TEST_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_ACE_CLIENT_TEST}
+    ${TARGET_ACE_LIB}
+    ${ACE_CLIENT_TEST_DEPS_LIBRARIES}
+    )
+
+INSTALL(TARGETS ${TARGET_ACE_CLIENT_TEST} DESTINATION /usr/bin)
diff --git a/tests/ace_client/ace_client_tests.cpp b/tests/ace_client/ace_client_tests.cpp
new file mode 100644 (file)
index 0000000..a8914fa
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_client_tests.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       Main executable file for ACE client tests.
+ */
+#include <dpl/log/log.h>
+#include <dpl/test/test_runner.h>
+
+int main(int argc, char *argv[]){
+    LogInfo("Starting tests");
+    int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
+    return status;
+}
diff --git a/tests/ace_client/test_cases.cpp b/tests/ace_client/test_cases.cpp
new file mode 100644 (file)
index 0000000..0408018
--- /dev/null
@@ -0,0 +1,1215 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    test_cases.cpp
+ * @author  Tonasz Swierczek (t.swierczek@samsung.com)
+ * @version 1.0
+ * @brief   Implementation file for ACE client test cases.
+ */
+#include <dpl/test/test_runner.h>
+#include <memory>
+
+#include "ace_client.h"
+#include "ace_api_client.h"
+#include "AceDAOReadOnly_mock.h"
+#include "communication_client_mock.h"
+#include "PolicyInformationPoint_mock.h"
+
+namespace {
+
+const char* featureName1 = "feature-1";
+const char* featureName2 = "feature-2";
+const char* devCapName1 = "devCap-1";
+const char* devCapName2 = "devCap-2";
+const char* devCapName3noSmack = "devCap-3-no-smack";
+const char* devCapName4noSmack = "devCap-4-no-smack";
+const char* devCapName5notRequested = "devCap-5-not-requested";
+const char* devCapName6notRequested = "devCap-6-not-requested";
+const char* devCap_EXTERNAL_NETWORK_ACCESS_DEV_CAP = "externalNetworkAccess";
+const char* devCap_XML_HTTP_REQUEST_ACCESS_DEV_CAP = "XMLHttpRequest";
+
+// UI callback function used for popups
+
+static ace_bool_t validation_result = ACE_TRUE;
+
+ace_return_t ace_popup_handler_func(ace_popup_t,
+                                    const ace_resource_t,
+                                    const ace_session_id_t,
+                                    const ace_param_list_t*,
+                                    ace_widget_handle_t,
+                                    ace_bool_t* validation)
+{
+    *validation = validation_result;
+    return ACE_OK;
+}
+
+enum class DevCapsToUse {
+    RequestedSmack,
+    RequestedNoSmack,
+    HTTP_XML_Requests,
+    NotRequested
+};
+
+enum class AceTestOptionalCachedPolicyResult {
+    UNDETERMINED,
+    NOT_APPLICABLE,
+    PROMPT_BLANKET,
+    PROMPT_SESSION,
+    PROMPT_ONESHOT,
+    PERMIT,
+    DENY,
+    NULL_VALUE
+};
+
+enum class AceTestPolicyResult {
+    UNDETERMINED,
+    NOT_APPLICABLE,
+    PROMPT_BLANKET,
+    PROMPT_SESSION,
+    PROMPT_ONESHOT,
+    PERMIT,
+    DENY
+};
+
+enum class AceTestOptionalCachedPromptDecision {
+    ALLOW_ALWAYS,
+    DENY_ALWAYS,
+    ALLOW_THIS_TIME,
+    DENY_THIS_TIME,
+    ALLOW_FOR_SESSION,
+    DENY_FOR_SESSION,
+    NULL_VALUE
+};
+
+static void configureTest(
+    AceTestOptionalCachedPolicyResult cachedPolicyResult,
+    AceTestOptionalCachedPromptDecision cachedPromptDecision,
+    const std::string& cachedPromptSession,
+    AceTestPolicyResult securityDaemonPolicyResult,
+    bool popupResponse)
+{
+    // Cached decision from popups
+    switch (cachedPromptDecision) {
+    case AceTestOptionalCachedPromptDecision::ALLOW_ALWAYS: {
+        CachedPromptDecision decision;
+        decision.decision = PromptDecision::ALLOW_ALWAYS;
+        decision.session = DPL::FromUTF8String(cachedPromptSession);
+        AceDB::AceDAOReadOnly::setPromptDecision(
+                OptionalCachedPromptDecision(decision));
+        break; }
+    case AceTestOptionalCachedPromptDecision::DENY_ALWAYS: {
+        CachedPromptDecision decision;
+        decision.decision = PromptDecision::DENY_ALWAYS;
+        decision.session = DPL::FromUTF8String(cachedPromptSession);
+        AceDB::AceDAOReadOnly::setPromptDecision(
+                        OptionalCachedPromptDecision(decision));
+        break; }
+    case AceTestOptionalCachedPromptDecision::ALLOW_THIS_TIME: {
+        CachedPromptDecision decision;
+        decision.decision = PromptDecision::ALLOW_THIS_TIME;
+        decision.session = DPL::FromUTF8String(cachedPromptSession);
+        AceDB::AceDAOReadOnly::setPromptDecision(
+                        OptionalCachedPromptDecision(decision));
+        break; }
+    case AceTestOptionalCachedPromptDecision::DENY_THIS_TIME: {
+        CachedPromptDecision decision;
+        decision.decision = PromptDecision::DENY_THIS_TIME;
+        decision.session = DPL::FromUTF8String(cachedPromptSession);
+        AceDB::AceDAOReadOnly::setPromptDecision(
+                        OptionalCachedPromptDecision(decision));
+        break; }
+    case AceTestOptionalCachedPromptDecision::ALLOW_FOR_SESSION: {
+        CachedPromptDecision decision;
+        decision.decision = PromptDecision::ALLOW_FOR_SESSION;
+        decision.session = DPL::FromUTF8String(cachedPromptSession);
+        AceDB::AceDAOReadOnly::setPromptDecision(
+                        OptionalCachedPromptDecision(decision));
+        break; }
+    case AceTestOptionalCachedPromptDecision::DENY_FOR_SESSION: {
+        CachedPromptDecision decision;
+        decision.decision = PromptDecision::DENY_FOR_SESSION;
+        decision.session = DPL::FromUTF8String(cachedPromptSession);
+        AceDB::AceDAOReadOnly::setPromptDecision(
+                        OptionalCachedPromptDecision(decision));
+        break; }
+    case AceTestOptionalCachedPromptDecision::NULL_VALUE:
+    default : {
+        AceDB::AceDAOReadOnly::setPromptDecision(
+                OptionalCachedPromptDecision());
+        break; }
+    }
+
+    // Daemon response
+    switch (securityDaemonPolicyResult) {
+    case AceTestPolicyResult::UNDETERMINED: {
+        WrtSecurity::Communication::Client::setCheckAccessResult(PolicyResult::serialize(
+                PolicyResult(PolicyResult::Value::UNDETERMINED)));
+        break; }
+    case AceTestPolicyResult::NOT_APPLICABLE: {
+        WrtSecurity::Communication::Client::setCheckAccessResult(PolicyResult::serialize(
+                PolicyResult()));
+        break; }
+    case AceTestPolicyResult::PROMPT_BLANKET: {
+        WrtSecurity::Communication::Client::setCheckAccessResult(PolicyResult::serialize(
+                PolicyResult(PolicyEffect::PROMPT_BLANKET)));
+        break; }
+    case AceTestPolicyResult::PROMPT_SESSION: {
+        WrtSecurity::Communication::Client::setCheckAccessResult(PolicyResult::serialize(
+                PolicyResult(PolicyEffect::PROMPT_SESSION)));
+        break; }
+    case AceTestPolicyResult::PROMPT_ONESHOT: {
+        WrtSecurity::Communication::Client::setCheckAccessResult(PolicyResult::serialize(
+                PolicyResult(PolicyEffect::PROMPT_ONESHOT)));
+        break; }
+    case AceTestPolicyResult::PERMIT: {
+        WrtSecurity::Communication::Client::setCheckAccessResult(PolicyResult::serialize(
+                PolicyResult(PolicyEffect::PERMIT)));
+        break; }
+    case AceTestPolicyResult::DENY: {
+        WrtSecurity::Communication::Client::setCheckAccessResult(PolicyResult::serialize(
+                PolicyResult(PolicyEffect::DENY)));
+        break; }
+    default: {
+        WrtSecurity::Communication::Client::setCheckAccessResult(PolicyResult::serialize(
+                PolicyResult()));
+        break; }
+    }
+
+    // Not empty attribute set to be returned
+    AceDB::BaseAttributeSet attributeSet;
+    AceDB::BaseAttributePtr attribute(new AceDB::BaseAttribute());
+    std::string aname = "attribute-subject-name1";
+    attribute->setName(&aname);
+    attribute->setType(AceDB::BaseAttribute::Type::Subject);
+    attributeSet.insert(attribute);
+    AceDB::AceDAOReadOnly::setAttributeSet(attributeSet);
+
+    // Cached response
+    switch (cachedPolicyResult) {
+    case AceTestOptionalCachedPolicyResult::UNDETERMINED: {
+        AceDB::AceDAOReadOnly::setPolicyResult(
+                ExtendedPolicyResult(PolicyResult::Value::UNDETERMINED));
+        break; }
+    case AceTestOptionalCachedPolicyResult::NOT_APPLICABLE: {
+        AceDB::AceDAOReadOnly::setPolicyResult(
+                ExtendedPolicyResult(PolicyResult()));
+        break; }
+    case AceTestOptionalCachedPolicyResult::PROMPT_BLANKET: {
+        AceDB::AceDAOReadOnly::setPolicyResult(
+                ExtendedPolicyResult(PolicyEffect::PROMPT_BLANKET));
+        break; }
+    case AceTestOptionalCachedPolicyResult::PROMPT_SESSION: {
+        AceDB::AceDAOReadOnly::setPolicyResult(
+                ExtendedPolicyResult(PolicyEffect::PROMPT_SESSION));
+        break; }
+    case AceTestOptionalCachedPolicyResult::PROMPT_ONESHOT: {
+        AceDB::AceDAOReadOnly::setPolicyResult(
+                ExtendedPolicyResult(PolicyEffect::PROMPT_ONESHOT));
+        break; }
+    case AceTestOptionalCachedPolicyResult::PERMIT: {
+        AceDB::AceDAOReadOnly::setPolicyResult(
+                ExtendedPolicyResult(PolicyEffect::PERMIT));
+        break; }
+    case AceTestOptionalCachedPolicyResult::DENY: {
+        AceDB::AceDAOReadOnly::setPolicyResult(
+                ExtendedPolicyResult(PolicyEffect::DENY));
+        break; }
+    case AceTestOptionalCachedPolicyResult::NULL_VALUE:
+    default: {
+        AceDB::AceDAOReadOnly::setPolicyResult(OptionalExtendedPolicyResult());
+        break;
+        }
+    }
+
+    // Prompt decision/validation from UI handler function
+    validation_result = popupResponse ? ACE_TRUE : ACE_FALSE;
+
+    // Setting requested dev capps (for SMACK)
+    AceDB::RequestedDevCapsMap devCapPermissions;
+    devCapPermissions.insert(std::make_pair(DPL::FromASCIIString(devCapName1),true));
+    devCapPermissions.insert(std::make_pair(DPL::FromASCIIString(devCapName2),true));
+    devCapPermissions.insert(std::make_pair(DPL::FromASCIIString(devCapName3noSmack),false));
+    devCapPermissions.insert(std::make_pair(DPL::FromASCIIString(devCapName4noSmack),false));
+    AceDB::AceDAOReadOnly::setDevCapPermissions(devCapPermissions);
+
+    AceDB::FeatureNameVector fvector;
+    fvector.push_back(DPL::FromASCIIString(featureName1));
+    fvector.push_back(DPL::FromASCIIString(featureName2));
+    AceDB::AceDAOReadOnly::setAcceptedFeature(fvector);
+}
+
+static void fillRequest(AceClient::AceRequest &aceRequest,
+                        AceClient::AceSessionId sessionId,
+                        DevCapsToUse caps = DevCapsToUse::RequestedSmack)
+{
+    static const char* apiFeature[] = {featureName1, featureName2};
+    static const char* devCapNames[] = {devCapName2, devCapName1};
+    static const char* devCapNamesNoSmack[] = {devCapName3noSmack,
+                                              devCapName4noSmack};
+    static const char* devCapNamesNotReq[] = {devCapName5notRequested,
+                                              devCapName6notRequested};
+    static const char* devCapNamesHTTPXML[] =
+            {devCap_EXTERNAL_NETWORK_ACCESS_DEV_CAP,
+             devCap_XML_HTTP_REQUEST_ACCESS_DEV_CAP};
+
+    static AceClient::AceParamList paramList[2];
+    static AceClient::AceParam param("param1-name", "param1-value");
+
+    paramList[0].count = 1;
+    paramList[0].param = &param;
+    paramList[1].count = 1;
+    paramList[1].param = &param;
+
+    aceRequest.sessionId = sessionId;
+    aceRequest.widgetHandle = 0;
+    aceRequest.apiFeatures.count = 2;
+    aceRequest.apiFeatures.apiFeature = apiFeature;
+    aceRequest.functionName = "test-function-name";
+    aceRequest.deviceCapabilities.devcapsCount = 2;
+    switch(caps) {
+    case DevCapsToUse::RequestedSmack: {
+        aceRequest.deviceCapabilities.devCapNames = devCapNames;
+        break; }
+    case DevCapsToUse::RequestedNoSmack: {
+        aceRequest.deviceCapabilities.devCapNames = devCapNamesNoSmack;
+        break; }
+    case DevCapsToUse::NotRequested: {
+        aceRequest.deviceCapabilities.devCapNames = devCapNamesNotReq;
+        break; }
+    case DevCapsToUse::HTTP_XML_Requests: {
+        aceRequest.deviceCapabilities.devCapNames = devCapNamesHTTPXML;
+        break; }
+    }
+    aceRequest.deviceCapabilities.paramsCount = 2;
+    aceRequest.deviceCapabilities.params = paramList;
+}
+
+// New C API version of request setup
+static void fillCAPIRequest(ace_request_t &aceRequest,
+                            AceClient::AceSessionId sessionId,
+                            DevCapsToUse caps = DevCapsToUse::RequestedSmack)
+{
+    static const char* apiFeature[] = {featureName1, featureName2};
+    static const char* devCapNames[] = {devCapName2, devCapName1};
+    static const char* devCapNamesNoSmack[] = {devCapName3noSmack,
+                                              devCapName4noSmack};
+    static const char* devCapNamesNotReq[] = {devCapName5notRequested,
+                                              devCapName6notRequested};
+    static const char* devCapNamesHTTPXML[] =
+            {devCap_EXTERNAL_NETWORK_ACCESS_DEV_CAP,
+             devCap_XML_HTTP_REQUEST_ACCESS_DEV_CAP};
+
+    static std::string session = sessionId;
+
+    aceRequest.session_id = const_cast<char*>(session.c_str());
+    aceRequest.widget_handle = 0;
+    aceRequest.feature_list.count = 2;
+    aceRequest.feature_list.items = const_cast<char**>(apiFeature);
+
+    static ace_param_t param;
+    param.name = const_cast<char*>("param1-name");
+    param.value = const_cast<char*>("param1-value");
+
+    static ace_dev_cap_t devCapList[2];
+    devCapList[0].param_list.count = 1;
+    devCapList[1].param_list.count = 1;
+    devCapList[0].param_list.items = &param;
+    devCapList[1].param_list.items = &param;
+
+    aceRequest.dev_cap_list.count = 2;
+    aceRequest.dev_cap_list.items = devCapList;
+
+    switch(caps) {
+    case DevCapsToUse::RequestedSmack: {
+        aceRequest.dev_cap_list.items[0].name = const_cast<char*>(devCapNames[0]);
+        aceRequest.dev_cap_list.items[1].name = const_cast<char*>(devCapNames[1]);
+        break; }
+    case DevCapsToUse::RequestedNoSmack: {
+        aceRequest.dev_cap_list.items[0].name = const_cast<char*>(devCapNamesNoSmack[0]);
+        aceRequest.dev_cap_list.items[1].name = const_cast<char*>(devCapNamesNoSmack[1]);
+        break; }
+    case DevCapsToUse::NotRequested: {
+        aceRequest.dev_cap_list.items[0].name = const_cast<char*>(devCapNamesNotReq[0]);
+        aceRequest.dev_cap_list.items[1].name = const_cast<char*>(devCapNamesNotReq[1]);
+        break; }
+    case DevCapsToUse::HTTP_XML_Requests: {
+        aceRequest.dev_cap_list.items[0].name = const_cast<char*>(devCapNamesHTTPXML[0]);
+        aceRequest.dev_cap_list.items[1].name = const_cast<char*>(devCapNamesHTTPXML[1]);
+        break; }
+    }
+}
+
+// A macro for doing ACE check with new C API
+#define ACE_CHECK(req, exp_result)  {\
+    ace_bool_t ret = ACE_FALSE;\
+    RUNNER_ASSERT(ACE_OK == ace_check_access(&req, &ret));\
+    RUNNER_ASSERT(ret == exp_result);\
+}
+
+} // namespace
+
+RUNNER_TEST_GROUP_INIT(ACE_CLINET_TEST_SUITE)
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::isInitialized()
+ * purpose: tests proper initialization of singleton on first usage
+ */
+RUNNER_TEST(ace_client_test_01_initialization)
+{
+    AceClient::AceThinClient &client =
+                AceClient::AceThinClientSingleton::Instance();
+    RUNNER_ASSERT(client.isInitialized());
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests proper policy and prompt results given by ace client
+ * function should deny access to requested dev caps, even though there is
+ * cached PERMIT result, there is no smack rule given - security daemon should
+ * be called again and answer DENY
+ */
+RUNNER_TEST(ace_client_test_02_no_smack_rules)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session", DevCapsToUse::RequestedNoSmack);
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PERMIT,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::DENY,
+            false);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests proper behaviour for dev caps that are not directly
+ * mentioned in widgets confing like HTTP_XML_Requests. Two times function
+ * should check access, once with DENY (false) result, then with PERMIT (true)
+ */
+RUNNER_TEST(ace_client_test_03_xml_http_requests_dev_caps)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session", DevCapsToUse::HTTP_XML_Requests);
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PERMIT,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::PERMIT,
+            false);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::DENY,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::DENY,
+            false);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests proper behaviour for dev caps that are not directly
+ * mentioned in widgets confing, but that are not HTTP_XML_Requests.
+ * Function should check access and return with DENY (false).
+ */
+// Thin client no longer checks device-caps.
+// It will check only feature list.
+
+//RUNNER_TEST(ace_client_test_04_not_requested_dev_caps)
+//{
+//    AceClient::AceThinClient &client =
+//            AceClient::AceThinClientSingleton::Instance();
+//    AceClient::AceRequest aceRequest;
+//
+//    fillRequest(aceRequest, "this-session", DevCapsToUse::NotRequested);
+//
+//    configureTest(
+//            AceTestOptionalCachedPolicyResult::PERMIT,
+//            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+//            "this-session",
+//            AceTestPolicyResult::PERMIT,
+//            true);
+//    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+//}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when here are no cached values for policy
+ * results and for prompt answers. The security daemon should be asked and
+ * it should return PERMIT for first time, then DENY.
+ */
+RUNNER_TEST(ace_client_test_05_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::ALLOW_ALWAYS,
+            "this-session",
+            AceTestPolicyResult::PERMIT,
+            true);
+
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::ALLOW_ALWAYS,
+            "this-session",
+            AceTestPolicyResult::DENY,
+            true);
+
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when here are cached values for policy
+ * results (PERMIT and DENY case, no prompts).
+ */
+RUNNER_TEST(ace_client_test_06_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PERMIT,
+            AceTestOptionalCachedPromptDecision::ALLOW_ALWAYS,
+            "this-session",
+            AceTestPolicyResult::DENY,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::DENY,
+            AceTestOptionalCachedPromptDecision::ALLOW_ALWAYS,
+            "this-session",
+            AceTestPolicyResult::DENY,
+            true);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when here are cached values for policy
+ * results (PROMPT_BLANKET), but there is no cached value for prompt, so prompt
+ * should be opened, once returning DENY (false), second time PERMIT (true).
+ */
+RUNNER_TEST(ace_client_test_07_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    RUNNER_ASSERT(ACE_OK == ace_client_initialize(ace_popup_handler_func));
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_BLANKET,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::DENY,
+            false);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_BLANKET,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::DENY,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when here are cached values for both: policy
+ * results (PROMPT_BLANKET) and for prompt. Ace client should deny access for
+ * cached prompt DENY_FOR_SESSION answer and allow access for ALLOW_FOR_SESSION,
+ * given that session id ("this-session") is the same in cache as in request.
+ */
+RUNNER_TEST(ace_client_test_08_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    RUNNER_ASSERT(ACE_OK == ace_client_initialize(ace_popup_handler_func));
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_BLANKET,
+            AceTestOptionalCachedPromptDecision::DENY_FOR_SESSION,
+            "this-session",
+            AceTestPolicyResult::DENY,
+            true);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_BLANKET,
+            AceTestOptionalCachedPromptDecision::ALLOW_FOR_SESSION,
+            "this-session",
+            AceTestPolicyResult::DENY,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when here are cached values for both: policy
+ * results (PROMPT_BLANKET) and for prompt. Cached prompt decisions are remembered
+ * with another session id, but are *ALWAYS versions, so those are valid for
+ * incoming request. Ace client should first deny access (as there is
+ * DENY_ALWAYS in cache), and then allow (because of ALLOW_ALWAYS).
+ */
+RUNNER_TEST(ace_client_test_09_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    RUNNER_ASSERT(ACE_OK == ace_client_initialize(ace_popup_handler_func));
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_BLANKET,
+            AceTestOptionalCachedPromptDecision::DENY_ALWAYS,
+            "another-session",
+            AceTestPolicyResult::DENY,
+            true);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_BLANKET,
+            AceTestOptionalCachedPromptDecision::ALLOW_ALWAYS,
+            "another-session",
+            AceTestPolicyResult::DENY,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when here are cached values for both: policy
+ * results (PROMPT_SESSION and PROMPT_BLANKET) and for prompt.
+ * Cached prompt decisions are remembered with another session id and are
+ * *FOR_SESSION versions, meaning that there is efectively
+ * no prompt cache - popup needs to be called once again, and ace client
+ * needs to answer accordingly (first true (PERMIT), then false (DENY)).
+ */
+RUNNER_TEST(ace_client_test_10_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    RUNNER_ASSERT(ACE_OK == ace_client_initialize(ace_popup_handler_func));
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_SESSION,
+            AceTestOptionalCachedPromptDecision::DENY_FOR_SESSION,
+            "another-session",
+            AceTestPolicyResult::DENY,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_BLANKET,
+            AceTestOptionalCachedPromptDecision::ALLOW_FOR_SESSION,
+            "another-session",
+            AceTestPolicyResult::PERMIT,
+            false);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when here are cached values for both: policy
+ * results (PROMPT_SESSION) and for prompt. Cached prompt decisions are remembered
+ * with another session id and are *FOR_SESSION versions, meaning that there is
+ * efectively no prompt cache - popup needs to be called once again, and ace client
+ * needs to answer accordingly (first true (PERMIT), then false (DENY)).
+ */
+RUNNER_TEST(ace_client_test_11_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    RUNNER_ASSERT(ACE_OK == ace_client_initialize(ace_popup_handler_func));
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_SESSION,
+            AceTestOptionalCachedPromptDecision::DENY_FOR_SESSION,
+            "another-session",
+            AceTestPolicyResult::DENY,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_SESSION,
+            AceTestOptionalCachedPromptDecision::ALLOW_FOR_SESSION,
+            "another-session",
+            AceTestPolicyResult::PERMIT,
+            false);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+}
+
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when here are cached values for policy
+ * results (PROMPT_ONCE) and there is no cache (there should not be any).
+ * Ace client needs to return true/false based entirely on prompt result
+ * (first false, then true).
+ */
+RUNNER_TEST(ace_client_test_12_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    RUNNER_ASSERT(ACE_OK == ace_client_initialize(ace_popup_handler_func));
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_ONESHOT,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::PERMIT,
+            false);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_ONESHOT,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::DENY,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when here are not cached values for policy
+ * results, but security daemon responds with  PROMPT_ONCE policy result.
+ * There is alsi no prompt cache (there should not be any).
+ * Ace client needs to return true/false based entirely on prompt result
+ * (first false, then true).
+ */
+RUNNER_TEST(ace_client_test_13_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::PROMPT_ONESHOT,
+            false);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::PROMPT_ONESHOT,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when there is no policy cache and security
+ * daemon responds win undetermined/not applicable results - those should be
+ * treated as false (deny access).
+ */
+RUNNER_TEST(ace_client_test_14_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::UNDETERMINED,
+            true);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::NOT_APPLICABLE,
+            true);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when there is policy cache for
+ * PROMPT_BLANKET and no prompt cache present. Ace client should deny access
+ * because prompt is returning false.
+ */
+RUNNER_TEST(ace_client_test_15_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_BLANKET,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::UNDETERMINED,
+            false);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: tests how class behaves when there is not policy cache and
+ * no prompt cache present. Ace client should allow access
+ * because security daemon returns PROMPT_BLANKET, and prompt is returning true.
+ */
+RUNNER_TEST(ace_client_test_16_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::PROMPT_BLANKET,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::checkFunctionCall()
+ * purpose: Mixed tests for:
+ * 1) cached prompt and policy result (DENY_FOR_SESSION) with matching
+ * session id (should disallow access)
+ * 2) cached undetermined policy result (should disallow access)
+ * 3) cached not applicable policy result (should disallow access)
+ */
+RUNNER_TEST(ace_client_test_17_check_access)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_SESSION,
+            AceTestOptionalCachedPromptDecision::DENY_FOR_SESSION,
+            "this-session",
+            AceTestPolicyResult::PERMIT,
+            true);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::UNDETERMINED,
+            AceTestOptionalCachedPromptDecision::ALLOW_FOR_SESSION,
+            "another-session",
+            AceTestPolicyResult::PERMIT,
+            true);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NOT_APPLICABLE,
+            AceTestOptionalCachedPromptDecision::ALLOW_FOR_SESSION,
+            "another-session",
+            AceTestPolicyResult::PERMIT,
+            true);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: AceClient::AceThinClient::getWidgetResourcePreference(),
+ * AceClient::AceThinClient::getGlobalResourcesPreferences()
+ * purpose: Tests mapping between AceDB::PreferenceTypes and
+ * AceClient::AcePreference.
+ */
+RUNNER_TEST(ace_client_test_18_resource_preferences)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceWidgetHandle handle = 0;
+    AceClient::AceResource resource = "resource";
+    AceClient::AceResource resource2 = "resource2";
+
+    AceDB::AceDAOReadOnly::setWidgetDevCapSetting(
+            AceDB::PreferenceTypes::PREFERENCE_BLANKET_PROMPT);
+    RUNNER_ASSERT(client.getWidgetResourcePreference(resource,handle) ==
+            AceClient::AcePreference::PREFERENCE_BLANKET_PROMPT);
+    AceDB::AceDAOReadOnly::setWidgetDevCapSetting(
+            AceDB::PreferenceTypes::PREFERENCE_DEFAULT);
+    RUNNER_ASSERT(client.getWidgetResourcePreference(resource,handle) ==
+            AceClient::AcePreference::PREFERENCE_DEFAULT);
+    AceDB::AceDAOReadOnly::setWidgetDevCapSetting(
+            AceDB::PreferenceTypes::PREFERENCE_DENY);
+        RUNNER_ASSERT(client.getWidgetResourcePreference(resource,handle) ==
+            AceClient::AcePreference::PREFERENCE_DENY);
+    AceDB::AceDAOReadOnly::setWidgetDevCapSetting(
+            AceDB::PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT);
+    RUNNER_ASSERT(client.getWidgetResourcePreference(resource,handle) ==
+            AceClient::AcePreference::PREFERENCE_ONE_SHOT_PROMPT);
+    AceDB::AceDAOReadOnly::setWidgetDevCapSetting(
+            AceDB::PreferenceTypes::PREFERENCE_PERMIT);
+    RUNNER_ASSERT(client.getWidgetResourcePreference(resource,handle) ==
+            AceClient::AcePreference::PREFERENCE_PERMIT);
+    AceDB::AceDAOReadOnly::setWidgetDevCapSetting(
+            AceDB::PreferenceTypes::PREFERENCE_SESSION_PROMPT);
+    RUNNER_ASSERT(client.getWidgetResourcePreference(resource,handle) ==
+            AceClient::AcePreference::PREFERENCE_SESSION_PROMPT);
+
+    AceDB::PreferenceTypesMap map;
+
+    AceDB::AceDAOReadOnly::setDevCapSettings(map);
+    std::unique_ptr<AceClient::AceResourcesPreferences> ret(client.getGlobalResourcesPreferences());
+
+    RUNNER_ASSERT(ret->empty());
+
+    map.insert(make_pair(resource, AceDB::PreferenceTypes::PREFERENCE_PERMIT));
+    map.insert(make_pair(resource2, AceDB::PreferenceTypes::PREFERENCE_DENY));
+
+    AceDB::AceDAOReadOnly::setDevCapSettings(map);
+    ret.reset(client.getGlobalResourcesPreferences());
+    RUNNER_ASSERT(2 == ret->size());
+    AceClient::AceResourcesPreferences::iterator it;
+    it = ret->find(resource);
+    RUNNER_ASSERT((it->second) == AceClient::AcePreference::PREFERENCE_PERMIT);
+    it = ret->find(resource2);
+    RUNNER_ASSERT((it->second) == AceClient::AcePreference::PREFERENCE_DENY);
+
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: ace_client_initialize(),
+ * ace_check_access(), ace_client_shutdown()
+ * purpose: New C-API tests. Two ACE checks for prompt one shot. One should
+ * deny access as prompt is returning ACE_FALSE, second should pass because
+ * of ACE_TRUE returned from prompt function. Also, Ace check library should
+ * properly initialize and deinitialize itself.
+ */
+RUNNER_TEST(ace_client_test_19_check_access)
+{
+
+    RUNNER_ASSERT(ACE_OK == ace_client_initialize(ace_popup_handler_func));
+
+    ace_request_t aceRequest;
+
+    fillCAPIRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_ONESHOT,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::PERMIT,
+            false);
+
+    ACE_CHECK(aceRequest, ACE_FALSE);
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_ONESHOT,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::DENY,
+            true);
+
+    ACE_CHECK(aceRequest, ACE_TRUE);
+
+    RUNNER_ASSERT(ACE_OK == ace_client_shutdown());
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: ace_client_initialize(),
+ * ace_check_access(), ace_client_shutdown()
+ * purpose: New C-API tests. Two ACE checks for prompt one shot with policy
+ * result directly from daemon (no cache). One should
+ * deny access as prompt is returning ACE_FALSE, second should pass because
+ * of ACE_TRUE returned from prompt function. Also, Ace check library should
+ * properly initialize and deinitialize itself.
+ */
+RUNNER_TEST(ace_client_test_20_check_access)
+{
+    RUNNER_ASSERT(ACE_OK == ace_client_initialize(ace_popup_handler_func));
+
+    ace_request_t aceRequest;
+
+    fillCAPIRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::PROMPT_ONESHOT,
+            false);
+
+    ACE_CHECK(aceRequest, ACE_FALSE);
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "another-session",
+            AceTestPolicyResult::PROMPT_ONESHOT,
+            true);\
+
+    ACE_CHECK(aceRequest, ACE_TRUE);
+
+    RUNNER_ASSERT(ACE_OK == ace_client_shutdown());
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: ace_client_initialize(),
+ * ace_check_access(), ace_client_shutdown()
+ * purpose: New C-API tests. Two ACE checks for prompt blanket with policy
+ * result taken from cache. There is no prompt cache. One should
+ * deny access as prompt is returning ACE_FALSE, second should pass because
+ * of ACE_TRUE returned from prompt function. Also, Ace check library should
+ * properly initialize and deinitialize itself.
+ */
+RUNNER_TEST(ace_client_test_21_check_access)
+{
+    RUNNER_ASSERT(ACE_OK == ace_client_initialize(ace_popup_handler_func));
+
+    ace_request_t aceRequest;
+
+    fillCAPIRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_BLANKET,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::DENY,
+            false);
+    ACE_CHECK(aceRequest, ACE_FALSE);
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::PROMPT_BLANKET,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::DENY,
+            true);
+    ACE_CHECK(aceRequest, ACE_TRUE);
+
+    RUNNER_ASSERT(ACE_OK == ace_client_shutdown());
+}
+
+/*
+ * test author: Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * tested functions: checkFunctionCall(), checkFeatureList()
+ * purpose: We need to check list of api-feature connected with function.
+ * If non of the api-feature was requested by widget we should deny access.
+ * This call should success as both of the api-feature were reqested
+ * by widget.
+ */
+RUNNER_TEST(ace_client_test_22_checkFeatureList)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::PERMIT,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * tested functions: checkFunctionCall(), checkFeatureList()
+ * purpose: We need to check list of api-feature connected with function.
+ * If non of the api-feature was requested by widget we should deny access.
+ * This call should success as one of the api-feature required by function
+ * was reqested by widget.
+ */
+RUNNER_TEST(ace_client_test_23_checkFeatureList)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    const char* apiFeature[] = {"fake-feature-3", featureName2};
+
+    aceRequest.apiFeatures.apiFeature = apiFeature;
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::PERMIT,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * tested functions: checkFunctionCall(), checkFeatureList()
+ * purpose: We need to check list of api-feature connected with function.
+ * If non of the api-feature was requested by widget we should deny access.
+ * This call should success as one of the api-feature required by function
+ * was reqested by widget.
+ */
+RUNNER_TEST(ace_client_test_24_checkFeatureList)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    const char* apiFeature[] = {featureName1, "fake-feature-3"};
+
+    aceRequest.apiFeatures.apiFeature = apiFeature;
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::PERMIT,
+            true);
+    RUNNER_ASSERT(client.checkFunctionCall(aceRequest));
+
+}
+
+/*
+ * test author: Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * tested functions: checkFunctionCall(), checkFeatureList()
+ * purpose: We need to check list of api-feature connected with function.
+ * If non of the api-feature was requested by widget we should deny access.
+ * This call should fail as non of the api-feature required by function
+ * was reqested by widget.
+ */
+RUNNER_TEST(ace_client_test_25_checkFeatureList)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    const char* apiFeature[] = {"fake-feature-3", "fake-feature-4"};
+
+    aceRequest.apiFeatures.apiFeature = apiFeature;
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::PERMIT,
+            true);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+}
+
+/*
+ * test author: Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * tested functions: checkFunctionCall(), checkFeatureList()
+ * purpose: We need to check list of api-feature connected with function.
+ * If non of the api-feature was requested by widget we should deny access.
+ * This call should fail as api-feature required by function
+ * wasn't reqested by widget.
+ */
+RUNNER_TEST(ace_client_test_26_checkFeatureList)
+{
+    AceClient::AceThinClient &client =
+            AceClient::AceThinClientSingleton::Instance();
+    AceClient::AceRequest aceRequest;
+
+    fillRequest(aceRequest, "this-session");
+
+    const char* apiFeature[] = {"fake-feature-3"};
+
+    aceRequest.apiFeatures.count = 1;
+    aceRequest.apiFeatures.apiFeature = apiFeature;
+
+    configureTest(
+            AceTestOptionalCachedPolicyResult::NULL_VALUE,
+            AceTestOptionalCachedPromptDecision::NULL_VALUE,
+            "this-session",
+            AceTestPolicyResult::PERMIT,
+            true);
+    RUNNER_ASSERT(!client.checkFunctionCall(aceRequest));
+}
+
diff --git a/tests/ace_install/CMakeLists.txt b/tests/ace_install/CMakeLists.txt
new file mode 100644 (file)
index 0000000..7459958
--- /dev/null
@@ -0,0 +1,58 @@
+#
+#Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an "AS IS" BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @version     0.1
+#
+include(FindPkgConfig)
+
+SET(TARGET_ACE_INSTALL_TEST "wrt-tests-ace-install")
+
+PKG_CHECK_MODULES(ACE_INSTALL_TEST_DEPS
+    dpl-test-efl
+    dpl-db-efl
+    REQUIRED
+    )
+
+SET(ACE_INSTALL_TEST_SOURCES
+    ${PROJECT_SOURCE_DIR}/tests/ace_install/ace_install_tests.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace_install/test_cases.cpp
+    )
+
+SET(ACE_INSTALL_TEST_INCLUDES
+    ${ACE_INSTALL_DEPS_INCLUDE_DIRS}
+    ${PROJECT_SOURCE_DIR}/ace_install/include
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    ${PROJECT_SOURCE_DIR}/tests/ace_install
+    ${PROJECT_SOURCE_DIR}/ace/include
+    )
+
+ADD_DEFINITIONS(${ACE_INSTALL_TEST_DEPS_CFLAGS})
+ADD_DEFINITIONS(${ACE_INSTALL_TEST_CFLAGS_OTHER})
+ADD_DEFINITIONS(-D ACE_INSTALL_TESTS)
+
+INCLUDE_DIRECTORIES(${ACE_INSTALL_TEST_INCLUDES})
+
+ADD_EXECUTABLE(${TARGET_ACE_INSTALL_TEST} ${ACE_INSTALL_TEST_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_ACE_INSTALL_TEST}
+    ${TARGET_ACE_LIB}
+    ${TARGET_ACE_INSTALL_LIB}
+    ${ACE_INSTALL_TEST_DEPS_LIBRARIES}
+    )
+
+INSTALL(TARGETS ${TARGET_ACE_INSTALL_TEST} DESTINATION /usr/bin)
+INSTALL(FILES "ace-install-api-demo-policy.xml" DESTINATION /usr/etc/ace)
\ No newline at end of file
diff --git a/tests/ace_install/ace-install-api-demo-policy.xml b/tests/ace_install/ace-install-api-demo-policy.xml
new file mode 100644 (file)
index 0000000..5ea5efd
--- /dev/null
@@ -0,0 +1,29 @@
+<policy-set id="Policy-1" combine="first-matching-target">
+    <policy>
+
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="device-cap">
+                    resourcePermit
+                </resource-match>
+            </condition>
+        </rule>
+
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="device-cap">
+                    resourceDeny
+                </resource-match>
+            </condition>
+        </rule>
+
+        <rule effect="prompt-blanket">
+            <condition>
+                <resource-match attr="device-cap">
+                    resourcePrompt
+                </resource-match>
+            </condition>
+        </rule>
+
+    </policy>
+</policy-set>
diff --git a/tests/ace_install/ace_install_tests.cpp b/tests/ace_install/ace_install_tests.cpp
new file mode 100644 (file)
index 0000000..0e280cd
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_install_tests.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       Main executable file for ACE install tests.
+ */
+#include <dpl/log/log.h>
+#include <dpl/test/test_runner.h>
+
+int main(int argc, char *argv[]){
+    LogInfo("Starting tests");
+    int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
+    return status;
+}
diff --git a/tests/ace_install/test_cases.cpp b/tests/ace_install/test_cases.cpp
new file mode 100644 (file)
index 0000000..0d8bfdb
--- /dev/null
@@ -0,0 +1,393 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    test_cases.cpp
+ * @author  Tonasz Swierczek (t.swierczek@samsung.com)
+ * @version 1.0
+ * @brief   Implementation file for ACE install test cases.
+ */
+#include <string.h>
+#include <cstring>
+
+#include <dpl/test/test_runner.h>
+#include <dpl/log/log.h>
+
+#include "ace_api_install.h"
+#include "widget_installer.h"
+#include <ace-dao-ro/AceDAOReadOnly.h>
+
+RUNNER_TEST_GROUP_INIT(ACE_INSTALL_TEST_SUITE)
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: ace_install_initialize(),
+ * ace_install_shutdown()
+ * purpose: New C-API tests. Tests proper initialization and deinitialization
+ * of ace-install library.
+ */
+RUNNER_TEST(ace_install_test_01_initialization)
+{
+    RUNNER_ASSERT(ACE_OK == ace_install_initialize());
+    RUNNER_ASSERT(ACE_OK == ace_install_shutdown());
+    RUNNER_ASSERT(ACE_OK == ace_install_initialize());
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: ace_update_policy()
+ * purpose: New C-API tests. Tests proper policy re-parsing many times in a row.
+ */
+RUNNER_TEST(ace_install_test_02_policy_update)
+{
+    RUNNER_ASSERT(ACE_OK == ace_update_policy());
+    RUNNER_ASSERT(ACE_OK == ace_update_policy());
+    RUNNER_ASSERT(ACE_OK == ace_update_policy());
+}
+
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: ace_set_requested_dev_caps(),
+ * ace_get_requested_dev_caps(), ace_free_requested_dev_caps()
+ * purpose: New C-API tests. Tests proper setting and getting widget dev caps
+ * upon installation.
+ */
+RUNNER_TEST(ace_install_test_03_requested_dev_caps)
+{
+    ace_widget_handle_t handle = InstallerMockup::registerWidget();
+    ace_requested_dev_cap_t reqDevCaps[2];
+    reqDevCaps[0].device_capability = "dev-cap1";
+    reqDevCaps[0].smack_granted = ACE_TRUE;
+    reqDevCaps[1].device_capability = "dev-cap2";
+    reqDevCaps[1].smack_granted = ACE_FALSE;
+    ace_requested_dev_cap_list_t caps;
+    caps.count = 2;
+    caps.items = reqDevCaps;
+    RUNNER_ASSERT(ACE_OK == ace_set_requested_dev_caps(handle, &caps));
+    ace_requested_dev_cap_list_t capsGotFromDB;
+    RUNNER_ASSERT(ACE_OK == ace_get_requested_dev_caps(handle, &capsGotFromDB));
+    RUNNER_ASSERT(capsGotFromDB.count == caps.count);
+    unsigned int i;
+    bool one = false, two = false;
+    for (i = 0; i < capsGotFromDB.count; ++i) {
+        if (0 == strcmp(capsGotFromDB.items[i].device_capability,
+                                 caps.items[0].device_capability)) {
+            RUNNER_ASSERT(capsGotFromDB.items[i].smack_granted ==
+                        caps.items[0].smack_granted);
+            one = true;
+        } else {
+            RUNNER_ASSERT(capsGotFromDB.items[i].smack_granted ==
+                                    caps.items[1].smack_granted);
+            RUNNER_ASSERT(0 == strcmp(capsGotFromDB.items[i].device_capability,
+                                 caps.items[1].device_capability));
+            two = true;
+        }
+    }
+    RUNNER_ASSERT(one && two);
+    RUNNER_ASSERT(ACE_OK == ace_free_requested_dev_caps(&capsGotFromDB));
+}
+
+/*
+ * test author: Andrzej Surdej (a.surdej@gmail.com)
+ * tested functions: ace_register_widget(),
+ * ace_unregister_widget()
+ * purpose: New C-API tests. Tests proper setting and getting widget info.
+ */
+namespace {
+    int widgetHandle = 1000;
+    std::string testAuthor = "someAwesomeProgrammer;)";
+    std::string testVersion = "1.1.1R";
+    std::string widgetGuid = "http://widgets.org/myTestWidget";
+    std::string widgetShareHref = "http://shareWithOtherNiggers.ny.wrong";
+}
+
+/*
+ * author:
+ * test: ace_register_widget(), ace_unregister_widget()
+ * description: Try to install and uninstall widget with all correct info.
+ * expect: widget should be installed and uninstalled correctly.
+ */
+RUNNER_TEST(ace_install_test_04_correct_widget_info)
+{
+    struct widget_info info;
+    info.author = strdup(testAuthor.c_str());
+    info.id = strdup(widgetGuid.c_str());
+    info.type = WAC20;
+    info.version = strdup(testVersion.c_str());
+    info.shareHerf = strdup(widgetShareHref.c_str());
+
+    ace_return_t retValue = ace_register_widget(widgetHandle, &info, NULL);
+
+    //clean up before asserts
+    free(info.author);
+    free(info.id);
+    free(info.version);
+    free(info.shareHerf);
+
+    RUNNER_ASSERT(ACE_OK == retValue);
+    RUNNER_ASSERT(AceDB::AceDAOReadOnly::isWidgetInstalled(widgetHandle));
+
+    std::string gotVersion = AceDB::AceDAOReadOnly::getVersion(widgetHandle);
+    RUNNER_ASSERT(gotVersion == testVersion);
+
+    std::string gotGuid = AceDB::AceDAOReadOnly::getGUID(widgetHandle);
+    RUNNER_ASSERT(gotGuid == widgetGuid);
+
+    std::string gotShareHref = AceDB::AceDAOReadOnly::getShareHref(widgetHandle);
+    RUNNER_ASSERT(gotShareHref == widgetShareHref);
+
+    RUNNER_ASSERT(AceDB::AceDAOReadOnly::getWidgetType(widgetHandle) == AppTypes::WAC20);
+    RUNNER_ASSERT(AceDB::AceDAOReadOnly::getAuthorName(widgetHandle) == testAuthor);
+
+    RUNNER_ASSERT(ACE_OK == ace_unregister_widget(widgetHandle));
+    RUNNER_ASSERT(!AceDB::AceDAOReadOnly::isWidgetInstalled(widgetHandle));
+}
+
+/*
+ * author:
+ * test: ace_register_widget(), ace_unregister_widget()
+ * description: Negative test. NULL widget data passed.
+ * expect: Widget should not be installed.
+ */
+RUNNER_TEST(ace_install_test_06_wrong_widget_info)
+{
+    ace_return_t retVal = ace_register_widget(widgetHandle, NULL, NULL);
+    RUNNER_ASSERT(retVal != ACE_OK);
+    RUNNER_ASSERT(!AceDB::AceDAOReadOnly::isWidgetInstalled(widgetHandle));
+    //just to be sure
+    ace_unregister_widget(widgetHandle);
+}
+
+/*
+ * author:
+ * test: ace_register_widget(), ace_unregister_widget()
+ * description: Check if the same widget can be installed twice.
+ * expect: First widget should be installed, second widget should NOT be installed.
+ */
+RUNNER_TEST(ace_install_test_07_twins)
+{
+    struct widget_info info;
+    info.author = strdup(testAuthor.c_str());
+    info.id = strdup(widgetGuid.c_str());
+    info.type = WAC20;
+    info.version = strdup(testVersion.c_str());
+    info.shareHerf = strdup(widgetShareHref.c_str());
+
+    ace_return_t retValue = ace_register_widget(widgetHandle, &info, NULL);
+
+    //clean up before asserts
+    free(info.author);
+    free(info.id);
+    free(info.version);
+    free(info.shareHerf);
+
+    RUNNER_ASSERT(ACE_OK == retValue);
+    RUNNER_ASSERT(AceDB::AceDAOReadOnly::isWidgetInstalled(widgetHandle));
+
+    retValue = ace_register_widget(widgetHandle, &info, NULL);
+    RUNNER_ASSERT(ACE_OK != retValue);
+
+    RUNNER_ASSERT(AceDB::AceDAOReadOnly::isWidgetInstalled(widgetHandle));
+    ace_unregister_widget(widgetHandle);
+}
+
+/*
+ * author:
+ * test: ace_register_widget(), got***.empty(), getWidgetType(), ace_unregister_widget()
+ * description: Installing Widget with NULL info
+ * expect: Widget should be installed, all data about widget should be empty.
+ */
+RUNNER_TEST(ace_install_test_08_empty_values)
+{
+    struct widget_info info;
+    info.author = NULL;
+    info.id = NULL;
+    info.type = Tizen;
+    info.version = NULL;
+    info.shareHerf = NULL;
+
+    ace_return_t retValue = ace_register_widget(widgetHandle, &info, NULL);
+
+    //clean up before asserts
+    free(info.author);
+    free(info.id);
+    free(info.version);
+    free(info.shareHerf);
+
+    RUNNER_ASSERT(ACE_OK == retValue);
+    RUNNER_ASSERT(AceDB::AceDAOReadOnly::isWidgetInstalled(widgetHandle));
+
+    std::string gotAuthor = AceDB::AceDAOReadOnly::getAuthorName(widgetHandle);
+    RUNNER_ASSERT(gotAuthor.empty());
+
+    std::string gotVersion = AceDB::AceDAOReadOnly::getVersion(widgetHandle);
+    RUNNER_ASSERT(gotVersion.empty());
+
+    std::string gotGuid = AceDB::AceDAOReadOnly::getGUID(widgetHandle);
+    RUNNER_ASSERT(gotGuid.empty());
+
+    std::string gotShareHref = AceDB::AceDAOReadOnly::getShareHref(widgetHandle);
+    RUNNER_ASSERT(gotShareHref.empty());
+
+    RUNNER_ASSERT(AceDB::AceDAOReadOnly::getWidgetType(widgetHandle) == AppTypes::Tizen);
+
+    RUNNER_ASSERT(ACE_OK == ace_unregister_widget(widgetHandle));
+    RUNNER_ASSERT(!AceDB::AceDAOReadOnly::isWidgetInstalled(widgetHandle));
+}
+
+namespace {
+    int chaniId0 = 1;
+    std::string commonName0 = "commonNameForZeroElement";
+    std::string md50 = "md5CertificateForZeroElement";
+    std::string sha0 = "shaCertificateForZeroElement";
+    ace_cert_owner_t owner0 = AUTHOR;
+    ace_cert_type_t type0 = ENDENTITY;
+
+    int chaniId1 = 2;
+    std::string commonName1 = "commonNameForFirstElement";
+    std::string md51 = "md5CertificateForFirstElement";
+    std::string sha1 = "shaCertificateForFirstElement";
+    ace_cert_owner_t owner1 = AUTHOR;
+    ace_cert_type_t type1 = ENDENTITY;
+
+    int chaniId2 = 3;
+    std::string commonName2 = "commonNameForSecondElement";
+    std::string md52 = "md5CertificateForSecondElement";
+    std::string sha2 = "shaCertificateForSecondElement";
+    ace_cert_owner_t owner2 = DISTRIBUTOR;
+    ace_cert_type_t type2 = ROOT;
+}
+
+/*
+ * author:
+ * test: ace_register_widget(), getKeyCommonNameList(), getKeyFingerprints()
+ * description: Check if certificate verification works well while widget installing. Also check saved certificate data.
+ * expect: Widget should be installed properly, all data from certificate should match.
+ */
+RUNNER_TEST(ace_install_test_09_certificate_list)
+{
+    struct widget_info info;
+    info.author = NULL;
+    info.id = NULL;
+    info.type = Tizen;
+    info.version = NULL;
+    info.shareHerf = NULL;
+
+    ace_certificate_data** certList = new ace_certificate_data*[4];
+    certList[3] = NULL; //last element
+
+    for (int i = 0; i < 3; ++i) {
+        certList[i] = new ace_certificate_data;
+    }
+    certList[0]->chain_id = chaniId0;
+    certList[0]->common_name = strdup(commonName0.c_str());
+    certList[0]->md5_fp = strdup(md50.c_str());
+    certList[0]->sha1_fp = strdup(sha0.c_str());
+    certList[0]->owner = owner0;
+    certList[0]->type = type0;
+
+    certList[1]->chain_id = chaniId1;
+    certList[1]->common_name = strdup(commonName1.c_str());
+    certList[1]->md5_fp = strdup(md51.c_str());
+    certList[1]->sha1_fp = strdup(sha1.c_str());
+    certList[1]->owner = owner1;
+    certList[1]->type = type1;
+
+    certList[2]->chain_id = chaniId2;
+    certList[2]->common_name = strdup(commonName2.c_str());
+    certList[2]->md5_fp = strdup(md52.c_str());
+    certList[2]->sha1_fp = strdup(sha2.c_str());
+    certList[2]->owner = owner2;
+    certList[2]->type = type2;
+
+    ace_return_t retValue = ace_register_widget(widgetHandle, &info, certList);
+
+    //clean up before asserts
+    free(info.author);
+    free(info.id);
+    free(info.version);
+    free(info.shareHerf);
+    for (int i = 0; i < 3; ++i) {
+        free(certList[i]->common_name);
+        free(certList[i]->md5_fp);
+        free(certList[i]->sha1_fp);
+        delete certList[i];
+    }
+    delete[] certList;
+
+    RUNNER_ASSERT(ACE_OK == retValue);
+    RUNNER_ASSERT(AceDB::AceDAOReadOnly::isWidgetInstalled(widgetHandle));
+
+    WidgetCertificateCNList commonNameList =
+        AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
+                                                    WidgetCertificateData::AUTHOR,
+                                                    WidgetCertificateData::ENDENTITY);
+    RUNNER_ASSERT(2 == commonNameList.size());
+    RUNNER_ASSERT(commonName0 == commonNameList.front() ||
+                  commonName0 == commonNameList.back());
+    RUNNER_ASSERT(commonName1 == commonNameList.front() ||
+                  commonName1 == commonNameList.back());
+    commonNameList.clear();
+    commonNameList =
+        AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
+                                                    WidgetCertificateData::DISTRIBUTOR,
+                                                    WidgetCertificateData::ROOT);
+    RUNNER_ASSERT(1 == commonNameList.size());
+    RUNNER_ASSERT(commonName2 == commonNameList.front());
+
+    FingerPrintList fpList =
+        AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
+                                                  WidgetCertificateData::AUTHOR,
+                                                  WidgetCertificateData::ENDENTITY);
+    RUNNER_ASSERT(4 == fpList.size());
+
+    fpList.clear();
+    fpList =
+        AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
+                                                  WidgetCertificateData::DISTRIBUTOR,
+                                                  WidgetCertificateData::ROOT);
+    RUNNER_ASSERT(2 == fpList.size());
+
+    ace_unregister_widget(widgetHandle);
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: ace_get_policy_result()
+ * purpose: New C-API tests. Tests proper policy evaluation by security daemon
+ * and successful passing data to ace-install library. For three calls,
+ * three results are expected: ACE_PERMIT, ACE_DENY and ACE_PROMPT.
+ */
+RUNNER_TEST(ace_install_test_10_policy_results)
+{
+    ace_widget_handle_t handle = InstallerMockup::registerWidget();
+    ace_resource_t resourceA = "resourcePermit";
+    ace_resource_t resourceB = "resourceDeny";
+    ace_resource_t resourceC = "resourcePrompt";
+    ace_policy_result_t result = ACE_UNDEFINED;
+    RUNNER_ASSERT(ACE_OK == ace_get_policy_result(resourceA,
+                                                  handle,
+                                                  &result));
+    RUNNER_ASSERT(ACE_PERMIT == result);
+    RUNNER_ASSERT(ACE_OK == ace_get_policy_result(resourceB,
+                                                  handle,
+                                                  &result));
+    RUNNER_ASSERT(ACE_DENY == result);
+    RUNNER_ASSERT(ACE_OK == ace_get_policy_result(resourceC,
+                                                  handle,
+                                                  &result));
+    RUNNER_ASSERT(ACE_PROMPT == result);
+}
diff --git a/tests/ace_install/widget_installer.h b/tests/ace_install/widget_installer.h
new file mode 100644 (file)
index 0000000..21b423d
--- /dev/null
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    widget_installer.h
+ * @author  Tomasz Swierczek (t.swierczek@samsung.com)
+ * @brief   Class that manages widget installation for ACE tests
+ */
+#ifndef _TESTS_ACE_WIDGET_INSTALLER_H_
+#define _TESTS_ACE_WIDGET_INSTALLER_H_
+
+#include <ace-dao-rw/AceDAO.h>
+#include <ace-dao-ro/common_dao_types.h>
+#include <sys/time.h>
+#include <ctime>
+#include <cstdlib>
+
+#define INVALID_WIDGET_HANDLE -1
+
+using namespace AceDB;
+
+namespace InstallerMockup {
+
+class WacSecurityMock : public IWacSecurity
+{
+public:
+    WacSecurityMock() :
+        mRecognized(false),
+        mDistributorSigned(false),
+        mWacSigned(false)
+    {
+    }
+
+    virtual const WidgetCertificateDataList& getCertificateList() const
+    {
+        return mList;
+    }
+
+    virtual bool isRecognized() const { return mRecognized; }
+    virtual bool isDistributorSigned() const { return mDistributorSigned; }
+    virtual bool isWacSigned() const { return mWacSigned; }
+    virtual void getCertificateChainList(CertificateChainList& /*lst*/) const {}
+    virtual void getCertificateChainList(CertificateChainList& /*lst*/,
+            CertificateSource /* source */) const {}
+
+    WidgetCertificateDataList& getCertificateListRef()
+    {
+        return mList;
+    }
+
+    void setRecognized(bool recognized) { mRecognized = recognized; }
+    void setDistributorSigned(bool distributorSigned)
+    {
+        mDistributorSigned = distributorSigned;
+    }
+    void setWacSigned(bool wacSigned) { mWacSigned = wacSigned; }
+
+private:
+    WidgetCertificateDataList mList;
+    // author signature verified
+    bool mRecognized;
+    // known distribuor
+    bool mDistributorSigned;
+    // distributor is wac
+    bool mWacSigned;
+
+};
+
+static WidgetHandle _registerWidget(const WidgetRegisterInfo& regInfo,
+                                    const IWacSecurity& sec,
+                                    int line)
+{
+    //randomize widget handle
+    WidgetHandle handle = INVALID_WIDGET_HANDLE;
+    struct timeval tv;
+    gettimeofday(&tv, NULL);
+    srand(time(NULL) + tv.tv_usec);
+    do {
+        handle = rand();
+    } while (AceDAOReadOnly::isWidgetInstalled(handle));
+
+    try
+    {
+        auto previous = AceDAOReadOnly::getHandleList();
+
+        // register widget
+        AceDAO::registerWidgetInfo(handle, regInfo, sec.getCertificateList());
+
+        RUNNER_ASSERT_MSG(handle != INVALID_WIDGET_HANDLE,
+                          "(called from line " << line << ")");
+
+        auto current = AceDAOReadOnly::getHandleList();
+        RUNNER_ASSERT_MSG(previous.size()+1 == current.size(),
+                          "(called from line " << line << ")");
+
+        RUNNER_ASSERT_MSG(AceDAOReadOnly::isWidgetInstalled(handle),
+                          "(called from line " << line << ")");
+    } catch (AceDAOReadOnly::Exception::DatabaseError) {
+        RUNNER_ASSERT_MSG(
+                false,
+                "Unexpected exception (called from line " << line << ")");
+    }
+    return handle;
+}
+
+WidgetHandle registerWidget(AppTypes appType = AppTypes::WAC20)
+{
+    WacSecurityMock sec;
+    WidgetRegisterInfo regInfo;
+    regInfo.type = appType;
+    return _registerWidget(regInfo, sec, __LINE__);
+}
+
+} // namespace
+
+#endif // _TESTS_ACE_WIDGET_INSTALLER_H_
diff --git a/tests/ace_settings/CMakeLists.txt b/tests/ace_settings/CMakeLists.txt
new file mode 100644 (file)
index 0000000..09b9883
--- /dev/null
@@ -0,0 +1,55 @@
+#
+#Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an "AS IS" BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @version     0.1
+#
+include(FindPkgConfig)
+
+SET(TARGET_ACE_SETTINGS_TEST "wrt-tests-ace-settings")
+
+PKG_CHECK_MODULES(ACE_SETTINGS_TEST_DEPS
+    dpl-test-efl
+    dpl-db-efl
+    REQUIRED
+    )
+
+SET(ACE_SETTINGS_TEST_SOURCES
+    ${PROJECT_SOURCE_DIR}/tests/ace_settings/ace_settings_tests.cpp
+    ${PROJECT_SOURCE_DIR}/tests/ace_settings/test_cases.cpp
+    )
+
+SET(ACE_SETTINGS_TEST_INCLUDES
+    ${ACE_SETTINGS_DEPS_INCLUDE_DIRS}
+    ${PROJECT_SOURCE_DIR}/ace_settings/include
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    )
+
+ADD_DEFINITIONS(${ACE_SETTINGS_TEST_DEPS_CFLAGS})
+ADD_DEFINITIONS(${ACE_SETTINGS_TEST_CFLAGS_OTHER})
+ADD_DEFINITIONS(-D ACE_SETTINGS_TESTS)
+
+INCLUDE_DIRECTORIES(${ACE_SETTINGS_TEST_INCLUDES})
+
+ADD_EXECUTABLE(${TARGET_ACE_SETTINGS_TEST} ${ACE_SETTINGS_TEST_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_ACE_SETTINGS_TEST}
+    ${TARGET_ACE_LIB}
+    ${TARGET_ACE_SETTINGS_LIB}
+    ${ACE_SETTINGS_TEST_DEPS_LIBRARIES}
+    )
+
+INSTALL(TARGETS ${TARGET_ACE_SETTINGS_TEST} DESTINATION /usr/bin)
\ No newline at end of file
diff --git a/tests/ace_settings/ace_settings_tests.cpp b/tests/ace_settings/ace_settings_tests.cpp
new file mode 100644 (file)
index 0000000..9f68141
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        ace_settings_tests.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       Main executable file for ACE settings tests.
+ */
+#include <dpl/log/log.h>
+#include <dpl/test/test_runner.h>
+
+int main(int argc, char *argv[]){
+    LogInfo("Starting tests");
+    int status = DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
+    return status;
+}
diff --git a/tests/ace_settings/test_cases.cpp b/tests/ace_settings/test_cases.cpp
new file mode 100644 (file)
index 0000000..d03a885
--- /dev/null
@@ -0,0 +1,178 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file    test_cases.cpp
+ * @author  Tonasz Swierczek (t.swierczek@samsung.com)
+ * @version 1.0
+ * @brief   Implementation file for ACE settings test cases.
+ */
+#include <dpl/test/test_runner.h>
+
+#include "ace_api_settings.h"
+
+namespace {
+
+static const char* resource1 = "resource1-name";
+static const char* resource2 = "resource2-name";
+static int handle1 = 0;
+static int handle2 = 1;
+static ace_preference_t preference1 = ACE_PREFERENCE_PERMIT;
+static ace_preference_t preference2 = ACE_PREFERENCE_BLANKET_PROMPT;
+
+} // namespace
+
+RUNNER_TEST_GROUP_INIT(ACE_SETTINGS_TEST_SUITE)
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: ace_settings_initialize(), ace_settings_shutdown()
+ * purpose: New C-API tests. Tests proper initialization and deinitialization
+ * of ace-settings library.
+ */
+RUNNER_TEST(ace_settings_test_01_initialization)
+{
+    RUNNER_ASSERT(ACE_OK == ace_settings_initialize());
+    RUNNER_ASSERT(ACE_OK == ace_settings_shutdown());
+    RUNNER_ASSERT(ACE_OK == ace_settings_initialize());
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: ace_set_global_resource_preference(),
+ * ace_get_global_resource_preference()
+ * purpose: New C-API tests. Tests setting and getting global per resource
+ * access preferences.
+ */
+RUNNER_TEST(ace_settings_test_02_global_preferences)
+{
+    RUNNER_ASSERT(ACE_OK == ace_set_global_resource_preference(
+            const_cast<char*>(resource1), preference1));
+    ace_preference_t pref;
+    RUNNER_ASSERT(ACE_OK == ace_get_global_resource_preference(
+            const_cast<char*>(resource1), &pref));
+    RUNNER_ASSERT(preference1 == pref);
+
+    RUNNER_ASSERT(ACE_OK == ace_set_global_resource_preference(
+            const_cast<char*>(resource2), preference2));
+    RUNNER_ASSERT(ACE_OK == ace_get_global_resource_preference(
+            const_cast<char*>(resource2), &pref));
+    RUNNER_ASSERT(preference2 == pref);
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: ace_set_widget_resource_preference(),
+ * ace_get_widget_resource_preference()
+ * purpose: New C-API tests. Tests setting and getting per widget/resource
+ * access preferences.
+ */
+RUNNER_TEST(ace_settings_test_03_widget_preferences)
+{
+    RUNNER_ASSERT(ACE_OK == ace_set_widget_resource_preference(handle1,
+            const_cast<char*>(resource1),
+            preference1));
+    ace_preference_t pref;
+    RUNNER_ASSERT(ACE_OK == ace_get_widget_resource_preference(handle1,
+            const_cast<char*>(resource1),
+            &pref));
+    RUNNER_ASSERT(preference1 == pref);
+
+    RUNNER_ASSERT(ACE_OK == ace_set_widget_resource_preference(handle2,
+            const_cast<char*>(resource2),
+            preference2));
+    RUNNER_ASSERT(ACE_OK == ace_get_widget_resource_preference(handle2,
+            const_cast<char*>(resource2),
+            &pref));
+    RUNNER_ASSERT(preference2 == pref);
+}
+
+/*
+ * test author: Tomasz Swierczek (t.swierczek@samsung.com)
+ * tested functions: ace_get_widget_resource_preference(),
+ * ace_get_global_resource_preference(),
+ * ace_reset_widget_resource_settings(),
+ * ace_reset_global_resource_settings()
+ * purpose: New C-API tests. Tests proper resetting of settings database.
+ */
+RUNNER_TEST(ace_settings_test_04_database_reset)
+{
+    RUNNER_ASSERT(ACE_OK == ace_reset_widget_resource_settings());
+    RUNNER_ASSERT(ACE_OK == ace_reset_global_resource_settings());
+    ace_preference_t pref;
+    RUNNER_ASSERT(ACE_OK == ace_get_widget_resource_preference(handle1,
+            const_cast<char*>(resource1),
+            &pref));
+    RUNNER_ASSERT(ACE_PREFERENCE_DEFAULT == pref);
+    RUNNER_ASSERT(ACE_OK == ace_get_widget_resource_preference(handle2,
+            const_cast<char*>(resource2),
+            &pref));
+    RUNNER_ASSERT(ACE_PREFERENCE_DEFAULT == pref);
+    RUNNER_ASSERT(ACE_OK == ace_get_global_resource_preference(
+            const_cast<char*>(resource1),
+            &pref));
+    RUNNER_ASSERT(ACE_PREFERENCE_DEFAULT == pref);
+    RUNNER_ASSERT(ACE_OK == ace_get_global_resource_preference(
+            const_cast<char*>(resource2),
+            &pref));
+    RUNNER_ASSERT(ACE_PREFERENCE_DEFAULT == pref);
+}
+
+/*
+ * test author: Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * tested functions: ace_is_private_api
+ * purpose: This function should return true if device cap
+ * belongs to private api.
+ */
+RUNNER_TEST(ace_settings_test_05_private_api_positive)
+{
+    static const char *api_private[] = {
+        "bluetooth.admin",
+        "contact.read",
+        "nfc.tag",
+        NULL
+    };
+    for (int i=0; api_private[i]; ++i) {
+        ace_bool_t response = ACE_FALSE;
+        RUNNER_ASSERT(ACE_OK == ace_is_private_api(
+            const_cast<char*>(api_private[i]), &response));
+        RUNNER_ASSERT(ACE_TRUE == response);
+    }
+}
+
+/*
+ * test author: Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * tested functions: ace_is_private_api
+ * purpose: All calls should fail as non of the strings are connected with
+ * private api.
+ */
+RUNNER_TEST(ace_settings_test_06_private_api_negative)
+{
+    static const char *api_private[] = {
+        "bluetooth",
+        "contact.reed",
+        "nfc.tag.extended",
+        "totaly.fake",
+        NULL
+    };
+
+    for (int i=0; api_private[i]; ++i) {
+        ace_bool_t response = ACE_TRUE;
+        RUNNER_ASSERT(ACE_OK == ace_is_private_api(
+            const_cast<char*>(api_private[i]), &response));
+        RUNNER_ASSERT(ACE_FALSE == response);
+    }
+}
+
diff --git a/tests/geolocation_security/CMakeLists.txt b/tests/geolocation_security/CMakeLists.txt
new file mode 100644 (file)
index 0000000..5c009db
--- /dev/null
@@ -0,0 +1,43 @@
+ADD_CUSTOM_COMMAND(OUTPUT
+    geolocationSecurityTest1.wgt
+    geolocationSecurityTest2.wgt
+    COMMAND ${PROJECT_SOURCE_DIR}/tests/geolocation_security/createGeolocationSecurityTest.sh
+#    COMMAND mv ${PROJECT_SOURCE_DIR}/tests/geolocation_security/*wgt ${CMAKE_CURRENT_BINARY_DIR}
+    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/tests/geolocation_security/ 
+    DEPENDS createGeolocationSecurityTest.sh
+)
+
+ADD_CUSTOM_TARGET(WTF ALL DEPENDS geolocationSecurityTest1.wgt geolocationSecurityTest2.wgt)
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/tests/geolocation_security/GeolocationPolicyTest1
+    ${PROJECT_SOURCE_DIR}/tests/geolocation_security/GeolocationPolicyTest2
+    DESTINATION /usr/etc/ace
+    PERMISSIONS OWNER_READ
+                OWNER_WRITE
+                GROUP_READ
+                WORLD_READ
+    )
+
+
+INSTALL(FILES
+    ${CMAKE_CURRENT_BINARY_DIR}/geolocationSecurityTest1.wgt
+    ${CMAKE_CURRENT_BINARY_DIR}/geolocationSecurityTest2.wgt
+    DESTINATION /opt/apps/widget/tests/geolocation
+    PERMISSIONS OWNER_READ
+                OWNER_WRITE
+                GROUP_READ
+                WORLD_READ
+    )
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/tests/geolocation_security/wrt-tests-security-geolocation.sh
+    DESTINATION bin
+    PERMISSIONS OWNER_READ
+                OWNER_WRITE
+                OWNER_EXECUTE
+                GROUP_READ
+                GROUP_EXECUTE
+                WORLD_READ
+                WORLD_EXECUTE
+    )
diff --git a/tests/geolocation_security/GeolocationPolicyTest1 b/tests/geolocation_security/GeolocationPolicyTest1
new file mode 100644 (file)
index 0000000..558f2dc
--- /dev/null
@@ -0,0 +1,5 @@
+<policy-set id="Policy-1" combine="first-matching-target">
+    <policy>
+        <rule effect="permit" />
+    </policy>
+</policy-set>
diff --git a/tests/geolocation_security/GeolocationPolicyTest2 b/tests/geolocation_security/GeolocationPolicyTest2
new file mode 100644 (file)
index 0000000..d22755a
--- /dev/null
@@ -0,0 +1,5 @@
+<policy-set id="Policy-1" combine="first-matching-target">
+    <policy>
+        <rule effect="deny" />
+    </policy>
+</policy-set>
diff --git a/tests/geolocation_security/createGeolocationSecurityTest.sh b/tests/geolocation_security/createGeolocationSecurityTest.sh
new file mode 100755 (executable)
index 0000000..0570afc
--- /dev/null
@@ -0,0 +1,42 @@
+#!/bin/sh
+
+#  wrt-plugins
+#
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+
+test_dir=./
+
+III=`pwd`
+echo "KATALOG: $III"
+
+cd $test_dir
+rm -f geolocationSecurityTest1.wgt
+rm -f geolocationSecurityTest2.wgt
+
+# remove vim template files
+rm -f `find . -name ".*.swp"`
+rm -f `find . -name "*~"`
+
+ORGPATH=`pwd`
+
+cd geolocationSecurityTest
+cp js/WAC2.0/TestGeolocationCallback1.js js/WAC2.0/TestGeolocationCallback.js
+cp config1.xml config.xml
+zip ../geolocationSecurityTest1.wgt -r *
+cp js/WAC2.0/TestGeolocationCallback2.js js/WAC2.0/TestGeolocationCallback.js
+cp config2.xml config.xml
+zip ../geolocationSecurityTest2.wgt -r *
+
diff --git a/tests/geolocation_security/geolocationSecurityTest/config1.xml b/tests/geolocation_security/geolocationSecurityTest/config1.xml
new file mode 100644 (file)
index 0000000..3d98b7b
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/geolocationSecurityTest1"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://www.w3.org/TR/geolocation-API/" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/geolocation_security/geolocationSecurityTest/config2.xml b/tests/geolocation_security/geolocationSecurityTest/config2.xml
new file mode 100644 (file)
index 0000000..4a7552e
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/geolocationSecurityTest2"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://www.w3.org/TR/geolocation-API/" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/geolocation_security/geolocationSecurityTest/css/style.css b/tests/geolocation_security/geolocationSecurityTest/css/style.css
new file mode 100755 (executable)
index 0000000..a4629be
--- /dev/null
@@ -0,0 +1,35 @@
+/* Add style information here */
+* {
+    padding: 0px;
+    margin: 0px;
+    color: #000;
+}
+
+#summary {
+    background-color: #ddd;
+    color: #000;
+    padding: 2px;
+}
+
+#log {
+    color: #fff;
+    width: 400px;
+    display: block;
+}
+
+#log .entry {
+    color: #fff;
+    padding: 2px;
+}
+
+#log .passed {
+    background-color: #45DE1B;
+}
+
+#log .failed {
+    background-color: #DE1B1B;
+}
+
+#log .exception {
+    background-color: #DE1BD8;
+}
diff --git a/tests/geolocation_security/geolocationSecurityTest/icon.png b/tests/geolocation_security/geolocationSecurityTest/icon.png
new file mode 100755 (executable)
index 0000000..b835ed1
Binary files /dev/null and b/tests/geolocation_security/geolocationSecurityTest/icon.png differ
diff --git a/tests/geolocation_security/geolocationSecurityTest/index.html b/tests/geolocation_security/geolocationSecurityTest/index.html
new file mode 100755 (executable)
index 0000000..2aa3d2f
--- /dev/null
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+    <head>
+        <title>Test engine</title>
+        <meta http-equiv="content-type"
+              content="text/html;charset=utf-8" />
+        <meta http-equiv="Content-Style-Type" content="text/css" />
+        <link rel="stylesheet" type="text/css" href="css/style.css" />
+        <script type="text/javascript" src="js/jquery.js"></script>
+        <!-- jquery.js has to be included first -->
+        <script type="text/javascript" src="js/include.js"></script>
+    </head>
+    <body bgColor="yellow" style="color:black;" onload="TestEngine.doTests();">
+        <div id="summary"></div>
+        <p id="log"></p>
+        <div id="video" style="background: red; width: 100%" />
+        TEST WIDGET
+   </body>
+</html>
+
diff --git a/tests/geolocation_security/geolocationSecurityTest/js/TestEngine.js b/tests/geolocation_security/geolocationSecurityTest/js/TestEngine.js
new file mode 100644 (file)
index 0000000..31c17bb
--- /dev/null
@@ -0,0 +1,1189 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test engine class.
+ *
+ * @author      Wojciech Bielawski(w.bielawski@samsung.com)
+ * @author      Pawel Misiak (p.misiak@samsung.com)
+ * @version     0.1
+ */
+
+var TestEngine = {
+    logText: "",
+    testCaseTimeout: 5 * 1000, //in miliseconds
+    currentCaseTimeout: 5 * 1000,
+    timer: null,
+    countOK: 0,
+    countErr: 0,
+    countException: 0,
+    countIgnored: 0,
+    currentFailings: [],
+    currentTestSuiteName: null,
+    callbackMutex: 0,
+    callbackMethodName: "",
+    currentTestCase: 0,
+    countAllPassed: 0,
+    countAllFailed: 0,
+    testCasesFailedCount: 0,
+    testCasesPassedCount: 0,
+    testCasesFailed: [],
+    testList: [],
+    finalLog: "\n",
+    testSuccessCallback: null,
+    testErrorCallback: null,
+    testSuiteName: null,
+    testSuiteStats: [],
+    resultLogger: new HTMLTestResultLogger('log'),
+    summaryRenderer: new HTMLTestSummaryRenderer('summary'),
+    finalCallback: null,
+
+    stepsArray: null,
+    stepTimeout: null,
+    currentStep: null,
+    errorType: null,
+    errorField: null,
+
+    /*
+     * Values used only as types representations.
+     */
+    STRING: '',
+    NUMBER: 0,
+    OBJECT: {},
+    ARRAY: [],
+    DATE: new Date(),
+    BOOL: false,
+    FUNCTION: function() {},
+
+    /*
+     * Error test possible results.
+     */
+    ERROR_TEST_RESULT: {
+      NOT_RUN: -4,
+      NOT_THROWN: -3,
+      BAD_TYPE: -2,
+      BAD_VALUE: -1,
+      OK: 0
+    },
+
+    /**
+     * Prints specified object in a TreeView like structure.
+     * @param obj Object to print.
+     * @param indent Must be undefined (don't pass anything).
+     */
+    dumpObject: function(obj, indent) {
+        if (indent === undefined) indent = '';
+        else indent += '   ';
+        var prefix = (indent.length == 0 ? indent : indent + '|--');
+        for (var i in obj) {
+            if (typeof(obj[i]) == "object") {
+                TestEngine.log(prefix + i + ":");
+                TestEngine.dumpObject(obj[i], indent);
+            }
+            else
+                TestEngine.log(prefix + i + ": " + obj[i]);
+        }
+    },
+
+    addTest: function(enabled, testFunc, testName, testPrereq)
+    {
+        if (null==testName) {
+            testName="unnamed test"
+        }
+        jsPrint("Add test: " + testName)
+        var data = new Object();
+        data.enabled = enabled;
+        data.testFunc = testFunc;
+        data.testName = testName;
+        data.testPrereq = testPrereq;
+        data.testSuite = TestEngine.testSuiteName;
+        // this.testList.push(testFunc)
+        this.testList.push(data);
+    },
+
+    setTestSuiteName: function(name, timeout)
+    {
+        this.testSuiteName = name;
+        this.testSuiteStats[name] = new Object();
+        this.testSuiteStats[name].passed = 0;
+        this.testSuiteStats[name].failed = 0;
+        this.testSuiteStats[name].assertsOK = 0;
+        this.testSuiteStats[name].assertsErr = 0;
+        TestEngine.currentCaseTimeout =
+            (timeout === undefined) ? TestEngine.testCaseTimeout : timeout;
+    },
+
+    setFinalCallback: function(finalCallbackParam)
+    {
+        this.finalCallback = finalCallbackParam;
+    },
+
+    log: function(text)
+    {
+        try
+        {
+            jsPrint(text);
+            this.logText += text + "<br/>";
+            this.finalLog += text + "\n";
+            // document.getElementById(TestEngine.currentTestSuite).innerHTML += text + "<br/>";
+            //document.getElementById('log').innerHTML += text + "<br/>";
+        }
+        catch(err)
+        {
+            this.countException++;
+            jsPrint("   TestEngine.log failure: " + err.message);
+        }
+    },
+
+    logException: function(text)
+    {
+        try
+        {
+            TestEngine.countException++;
+            TestEngine.log("[EXCEPTION] " + text);
+            TestEngine.currentFailings.push(text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logErr failure: " + err.message);
+        }
+    },
+
+    logErr: function(text)
+    {
+        try
+        {
+            TestEngine.countErr++;
+            TestEngine.log("[FAILED] " + text);
+            TestEngine.currentFailings.push(text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logErr failure: " + err.message);
+        }
+    },
+
+    logIgnored: function(text)
+    {
+        try
+        {
+            TestEngine.countIgnored++;
+            TestEngine.log("[IGNORED] " + text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logErr failure: " + err.message);
+        }
+    },
+
+    logOK: function(text)
+    {
+        try
+        {
+            TestEngine.countOK++;
+            TestEngine.log("[OK] " + text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logOK failure: " + err.message);
+        }
+    },
+
+    test: function(text, value)
+    {
+        try
+        {
+            if(typeof(value) == "undefined")
+            {
+                TestEngine.logErr("value not defined for test: '" + text + "'");
+            }
+            else if(!value)
+            {
+                TestEngine.logErr(text);
+            }
+            else
+            {
+                TestEngine.logOK(text);
+                return true;
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.test failure: " + err.message);
+        }
+        return false;
+    },
+
+    /**
+     * Sets error type used in every typePresetError check.
+     * @param type Type of an error/exception.
+     */
+    setErrorType: function(type)
+    {
+        TestEngine.errorType = type;
+    },
+
+    /**
+     * Sets error field used in every typePresetError check.
+     * @param field Name of the field in error structure to check its value.
+     */
+    setErrorField: function(field)
+    {
+        TestEngine.errorField = field;
+    },
+
+    /**
+     * Checks if specified expression throws a specified error.
+     * Expression must be enclosed in a function. Use setErrorType and
+     * setErrorField to set what error to look for.
+     * Error type must be set but if error field is left unset (i.e. null)
+     * then whole exception object is compared to specified value.
+     * @param msg Text to display for this test.
+     * @param fn Function eclosing the expression one wants to verify.
+     * @param value Value of an error/exception one looks for.
+     */
+    testPresetError: function(msg, fn, value)
+    {
+        if (TestEngine.errorType === null) {
+            TestEngine.logException("testPresetError skipped. Set error type first.");
+            return;
+        }
+
+        return TestEngine.testError(msg, fn, TestEngine.errorType,
+            TestEngine.errorField, value);
+    },
+
+    /**
+     * Checks if specified expression throws a specified error.
+     * This is a more general version of testPresetError function.
+     * Expression must be enclosed in a function.
+     * Error type must be set but if error field is left unset (i.e. null)
+     * then whole exception object is compared to specified value.
+     * @param msg Text to display for this test.
+     * @param fn Function eclosing the expression one wants to verify.
+     * @param errType Type of desired error/exception.
+     * @param errField Property from exception structure to look for exception
+     * value.
+     * @param errValue Value of an error/exception one looks for.
+     */
+    testError: function(msg, fn, errType, errField, errValue)
+    {
+        if (errType === null) {
+            TestEngine.logException("testError skipped. Error type can't be null.");
+            return TestEngine.ERROR_TEST_RESULT.NOT_RUN;
+        }
+
+        try {
+            fn();
+            TestEngine.logErr(msg + ' Exception has not been thrown.');
+            return TestEngine.ERROR_TEST_RESULT.NOT_THROWN;
+        }
+        catch (ex) {
+            if (ex instanceof errType) {
+                var exValue = (errField !== null ? ex[errField] : ex);
+                if (exValue === errValue) {
+                    TestEngine.logOK(msg + ' [' + errValue + ']');
+                    return TestEngine.ERROR_TEST_RESULT.OK;
+                }
+                else {
+                    TestEngine.logErr(msg + ' Exception is not of value ' + errValue);
+                    return TestEngine.ERROR_TEST_RESULT.BAD_VALUE;
+                }
+            }
+            else {
+                TestEngine.logErr(msg + ' Exception is of wrong type.');
+                return TestEngine.ERROR_TEST_RESULT.BAD_TYPE;
+            }
+        }
+    },
+
+    testPresence: function(text, object)
+    {
+        try
+        {
+            if(object === undefined)
+            {
+                TestEngine.logErr("value not defined. Name: " + text);
+            }
+            else
+            {
+                TestEngine.logOK("object " + text + " present");
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testPresence failure: " + err.message);
+        }
+    },
+
+    /**
+     * Checks whether object implements given property.
+     * In addition it also checks whether any exception (e.g. "Not Supported")
+     * is thrown.
+     * @param object Object to check property for.
+     * @param property Property to look for.
+     * @return True if object implements such property, false otherwise.
+     */
+    testPresence2: function(object, property)
+    {
+        var result = property in object;
+        if (result)
+        {
+            TestEngine.logOK("property " + property + " present");
+        }
+        else
+        {
+            TestEngine.logErr("property " + property + " absent");
+        }
+        return result;
+    },
+
+
+    /**
+     * Checks whether mainObj object equals templateObj object, property by
+     * property.
+     * Runs recursively through all the properties of templateObj object and
+     * checks if they exist and are equal to those in mainObj object.
+     * mainObj has to implement no less properties than templateObj.
+     * @param mainObj Object to check for properties implementation.
+     * @param templateObj Object to verify properties against.
+     * @return True if mainObj has at least the same properties as templateObj,
+     *         false otherwise.
+     */
+    checkObjectsEqual: function(mainObj, templateObj)
+    {
+        try
+        {
+            if ((!mainObj && templateObj) || (typeof(mainObj) != typeof(templateObj))) {
+                return false;
+            }
+            else if (isNumber(templateObj) || isString(templateObj) || isBoolean(templateObj)) {
+                return (mainObj === templateObj);
+            }
+            else if (isDate(templateObj)) {
+                return (mainObj.valueOf() === templateObj.valueOf());
+            }
+            else {
+                for (var i in templateObj) {
+                    if (!TestEngine.checkObjectsEqual(mainObj[i], templateObj[i])) {
+                        return false;
+                    }
+                }
+            }
+        }
+        catch(err)
+        {
+            TestEngine.logException("TestEngine.checkObjectsEqual failure: " + err.message);
+            return false;
+        }
+        return true;
+    },
+
+    // test properties of given object. Steps:
+    // - check name presence
+    // - check default value (if not null value passed)
+    // - check if name is writable
+    //
+    // description of properties array:
+    // [0] - property name
+    // [1] - default value - check if property equals given value
+    //          undefined or null - disable check
+    // [2] - value to do writability test - try to write given value
+    //          undefined or null - don't check writability
+    // [3] - indicates if property should be read-only
+    // [4] - assumed type, undefined value skips this check
+    testProperties: function(object, props)
+    {
+        var result = new Object();
+        try
+        {
+            for(var i in props)
+            {
+                var name = props[i][0];
+                var defaultVal = props[i][1];
+                var setVal = props[i][2];
+                var isReadonly = props[i][3];
+                var type = props[i][4];
+                var errors = TestEngine.countErr + TestEngine.countException;
+
+                if ((typeof(name) != "string") || (name == ""))
+                {
+                    TestEngine.logException("Property name not defined, skipping it.");
+                    continue;
+                }
+
+                result[name] = false;
+                if (TestEngine.testPresence2(object, name)) {
+                    if ((defaultVal != null) && (defaultVal !== undefined))
+                    {
+                        var isObjectEqual = TestEngine.checkObjectsEqual(object[name], defaultVal);
+                        TestEngine.test(name + " default value", isObjectEqual);
+                    }
+
+                    if ((setVal != null) && (setVal !== undefined))
+                    {
+                        // try-catch is needed when SetProperty returns 'false'
+                        if(setVal === defaultVal)
+                        {
+                            TestEngine.logException("Default value and set value are equal");
+                            continue;
+                        }
+                        try { object[name] = setVal; }
+                        catch (e) { }
+                        if (typeof(isReadonly) == "undefined")
+                        {
+                            TestEngine.test(name + " writability, reason: isReadonly not specified", false);
+                        }
+                        if (isReadonly)
+                        {
+                            TestEngine.test(name + " writability", object[name] != setVal);
+                        }
+                        else
+                        {
+                            var isObjectEqual = TestEngine.checkObjectsEqual(object[name], setVal);
+                            TestEngine.test(name + " writability", isObjectEqual);
+                        }
+                    }
+
+                    if (type !== undefined) {
+                        var isType = (typeof(object[name]) == typeof(type));
+                        if (typeof(type) == 'object') {
+                            if (isArray(type)) {
+                                isType = isArray(object[name]);
+                            }
+                            else if (isDate(type)) {
+                                isType = isDate(object[name]);
+                            }
+                        }
+                        TestEngine.test(name + " type check.", isType);
+                    }
+                }
+                if (errors == TestEngine.countErr + TestEngine.countException) {
+                    result[name] = true;
+                }
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testProperties failure: " + err.message);
+        }
+        return result;
+    },
+
+    startTestCase: function()
+    {
+        try
+        {
+            TestEngine.countOK = 0;
+            TestEngine.countErr = 0;
+            TestEngine.countException = 0;
+            TestEngine.countIgnored = 0;
+            TestEngine.currentFailings = [];
+            TestEngine.timer = setTimeout(TestEngine.timeout, TestEngine.currentCaseTimeout);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.startTestCase failure: " + err.message);
+        }
+
+    },
+
+    endTestCase: function(testCase)
+    {
+        try
+        {
+            if(this.timer === null)
+            {
+                return;
+            }
+
+            clearTimeout(this.timer);
+            this.log("");
+            var ignored = this.countIgnored > 0;
+            var failed = this.countErr || ((this.countOK+this.countErr)<1) || this.countException || ignored;
+
+            if (widget.__test) {
+                if (ignored) {
+                    widget.__test.collectIgnored(testCase.testName);
+                } else if (failed) {
+                    widget.__test.collectFail(testCase.testName, TestEngine.currentFailings.join('; '));
+                } else {
+                    widget.__test.collectPass(testCase.testName);
+                }
+            }
+            this.log("Test case " + (failed ? "FAILED" : "PASSED"));
+            this.log("Passed: " + this.countOK);
+            this.log("Failed: " + this.countErr);
+            if(this.countException)
+            {
+                this.log("Exception occured!");
+            }
+
+            this.countAllPassed += this.countOK;
+            this.countAllFailed += this.countErr;
+            this.testSuiteStats[testCase.testSuite].assertsOK += this.countOK;
+            this.testSuiteStats[testCase.testSuite].assertsErr += this.countErr;
+
+            if(failed)
+            {
+                TestEngine.testCasesFailedCount++;
+                this.testSuiteStats[testCase.testSuite].failed++;
+                if (isVerbose()) {
+                    TestEngine.testCasesFailed.push(testCase.testName);
+                }
+                TestEngine.resultLogger.logFail(testCase.testName);
+            }
+            else
+            {
+                TestEngine.testCasesPassedCount++;
+                this.testSuiteStats[testCase.testSuite].passed++;
+                TestEngine.resultLogger.logPass(testCase.testName);
+            }
+            TestEngine.summaryRenderer.render(TestEngine);
+        }
+        catch(err)
+        {
+            this.countException++;
+            jsPrint("   TestEngine.endTestCase failure:" + err.message);
+        }
+    },
+
+    timeout: function()
+    {
+        try
+        {
+            TestEngine.callbackMutex = 0;
+            TestEngine.logErr("Widget run timeout.", false);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.timeout failure:" + err.message);
+        }
+    },
+
+    /**
+     * Registers callbacks for asynchronous function.
+     *
+     * To avoid finish test case before callbacks will execute it's necessary
+     * to register callbacks in the engine.
+     *
+     * @param methodName Testcase name, suggested asynchronous function name.
+     * @param testSuccessCallback Callback that will be executed on success.
+     * @param testErrorCallback Callback that will be executed on failure.
+     * @param callbacksCount number of callbacks to register.
+     * @return An object with defined functions "successCallback" and "errorCallback" you
+     *          need to pass as arguments to asynchronous function  e.g.
+     *
+     * function success() {  }
+     * function failure() {  }
+     *
+     * {
+         *      var obj = TestEngine.registerCallback("myAsyncFunc", success, failure);
+         *      myAsyncFunc(obj.successCallback, obj.errorCallback);
+         * }
+     */
+    registerCallback: function(methodName, testSuccessCallback, testErrorCallback, callbacksCount)
+    {
+        try
+        {
+            if(callbacksCount !== undefined && callbacksCount > 0){
+                TestEngine.callbackMutex += callbacksCount;
+            }
+            else {
+                TestEngine.callbackMutex++;
+            }
+            TestEngine.callbackMethodName = methodName;
+            TestEngine.testSuccessCallback = testSuccessCallback;
+            TestEngine.testErrorCallback = testErrorCallback;
+
+            var retObj = new Object();
+            retObj.callbackMethodName = methodName;
+            retObj.testSuccessCallback = testSuccessCallback;
+            retObj.successCallback = function(param){
+                try
+                {
+                    if((typeof retObj.testSuccessCallback != "undefined") && (retObj.testSuccessCallback !== null))
+                    {
+                        retObj.testSuccessCallback(param);
+                    }
+                    else
+                    {
+                        TestEngine.logOK(retObj.callbackMethodName + " succeed");
+                    }
+                }
+                catch(err)
+                {
+                    TestEngine.countException++;
+                    jsPrint("   TestEngine.this.successCallback failure:" + err.message);
+                }
+                TestEngine.callbackMutex--;
+            };
+
+            retObj.testErrorCallback = testErrorCallback;
+            retObj.errorCallback = function(param){
+                try
+                {
+                    if((typeof retObj.testErrorCallback != "undefined") && (retObj.testErrorCallback !== null))
+                    {
+                        retObj.testErrorCallback(param);
+                    }
+                    else
+                    {
+                        TestEngine.logErr(retObj.callbackMethodName + " failed");
+                    }
+                }
+                catch(err)
+                {
+                    TestEngine.countException++;
+                    jsPrint("   TestEngine.retObj.errorCallback failure:" + err.message);
+                }
+                TestEngine.callbackMutex--;
+            };
+
+            return retObj;
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.registerCallback failure:" + err.message);
+        }
+    },
+
+    successCallback: function(params)
+    {
+        TestEngine.log("[Warning] Function TestEngine.successCallback deprecated");
+        try
+        {
+            TestEngine.callbackMutex--;
+            if(typeof TestEngine.testSuccessCallback != "undefined")
+            {
+                TestEngine.testSuccessCallback(params);
+            }
+            else
+            {
+                TestEngine.logOK(TestEngine.callbackMethodName + " succeed");
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.successCallback failure:" + err.message);
+        }
+    },
+
+    errorCallback: function(params)
+    {
+        TestEngine.log("[Warning] Function TestEngine.errorCallback deprecated");
+        try
+        {
+            TestEngine.callbackMutex--;
+            if(typeof TestEngine.testErrorCallback != "undefined")
+            {
+                TestEngine.testErrorCallback(params);
+            }
+            else
+            {
+                TestEngine.logErr(TestEngine.callbackMethodName + " failed");
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.errorCallback failure:" + err.message);
+        }
+    },
+
+    waitForCallback: function()
+    {
+        try
+        {
+            //    while( TestEngine.callbackMutex )
+            {
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.waitForCallback failure:" + err.message);
+        }
+    },
+
+    /*
+     * code - error code which is expected
+     * object - object which will be used to call method
+     * functionName - method name to call
+     * restArguments - rest arguments which will be passed to callback
+     *
+     * example:
+     * TestEngine.catchError(10001, bondi.messaging, findSMSs, succCallback, null, filter)
+     */
+    catchError: function(code, object, functionName, restArguments /* , ... */ )
+    {
+        try
+        {
+            TestEngine.log("TestEngine.catchError is DEPRECATED. Please use TestEngine.catchErrorType.");
+            var error;
+            try
+            {
+                var newArgs = []
+                for (var i=3;i<arguments.length;i++) {
+                    newArgs.push(arguments[i])
+                }
+                var retVal = null;
+                retVal = object[functionName].apply(object, newArgs);
+                TestEngine.logErr(functionName + " no error thrown");
+                return retVal;
+            }
+            catch(error)
+            {
+                TestEngine.testPresence("<error code from: " + functionName + ">", error.code);
+                TestEngine.test("Error number", error.code == code);
+                return;
+            }
+            TestEngine.logErr("Function " + functionName + " desn't throw");
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testError failure:" + err.message);
+        }
+    },
+
+    /*
+     * errorTypeName - attribute name of catched exception to compare with code
+     * code - error code which is expected
+     * object - object which will be used to call method
+     * functionName - method name to call
+     * restArguments - rest arguments which will be passed to callback
+     *
+     * example:
+     * TestEngine.catchErrorType("code", 10001, bondi.messaging, findSMSs, succCallback, null, filter)
+     */
+    catchErrorType: function(errorTypeName, code, object, functionName, restArguments /* , ... */ )
+    {
+        try
+        {
+            var error;
+            try
+            {
+                var newArgs = []
+                for (var i=4;i<arguments.length;i++) {
+                    newArgs.push(arguments[i])
+                }
+                var retVal = null;
+                if (arguments.length < 4) {
+                    TestEngine.logErr("Wrong catchErrorType usage.");
+                    return retVal;
+                }
+                retVal = object[functionName].apply(object, newArgs);
+                TestEngine.logErr(functionName + " no error thrown");
+                return retVal;
+            }
+            catch(error)
+            {
+                TestEngine.testPresence("<error code from: " + functionName + ">", error[errorTypeName]);
+                TestEngine.test("Error number", error[errorTypeName] == code);
+                return;
+            }
+            TestEngine.logErr("Function " + functionName + " desn't throw");
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testError failure:" + err.message);
+        }
+    },
+
+    // Executes step by step functions passed in steps array
+    // and waits after every execution time defined in timeInterval
+    executeSteps: function(steps, timeInterval)
+    {
+        try
+        {
+            if(typeof(timeInterval) == "undefined")
+            {
+                timeInterval = 100; //default value
+            }
+
+            TestEngine.stepsArray = steps;
+            TestEngine.stepTimeout = timeInterval;
+            TestEngine.currentStep = 0;
+            TestEngine.executeNextStep();
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.executeSteps failure:" + err.message);
+        }
+    },
+
+    executeNextStep: function()
+    {
+        try
+        {
+            if( TestEngine.stepsArray && (TestEngine.currentStep < TestEngine.stepsArray.length) )
+            {
+                if( isArray( TestEngine.stepsArray[ TestEngine.currentStep ] ) )
+                {
+                    TestEngine.stepsArray[ TestEngine.currentStep ][0]();
+                    setTimeout( TestEngine.executeNextStep, TestEngine.stepsArray[ TestEngine.currentStep ][1] );
+
+                }
+                else
+                {
+                    TestEngine.stepsArray[ TestEngine.currentStep ]();
+                    setTimeout( TestEngine.executeNextStep, TestEngine.stepTimeout );
+                }
+                TestEngine.currentStep++;
+            }
+            else
+            {
+                TestEngine.currentStep = null;
+                TestEngine.stepTimeout = null;
+                TestEngine.stepsArray = null;
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.executeNextStep failure:" + err.message);
+            jsPrint("   Current step:" + TestEngine.currentStep);
+
+            TestEngine.currentStep = null;
+            TestEngine.stepTimeout = null;
+            TestEngine.stepsArray = null;
+        }
+    },
+
+    enumerate: function(obj, level)
+    {
+        try
+        {
+            if(typeof level == "undefined")
+            {
+                TestEngine.log(obj + ":");
+                level = "";
+            }
+            for(i in obj)
+            {
+                if(!(typeof obj[i] == "object" || typeof obj[i] == "array"))
+                {
+                    TestEngine.log(level + i + " =  " + obj[i]);
+                }
+                else
+                {
+                    TestEngine.log(level + i + " =  ");
+                    TestEngine.enumerate(obj[i], level + "----");
+                }
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.enumerate failure:" + err.message);
+        }
+    },
+
+    doTests: function()
+    {
+        try
+        {
+            TestEngine.testCasesFailed = [];
+            TestEngine.test("jsPrint presence", jsPrint);
+            TestEngine.test("Widget presence", window.widget);
+            TestEngine.doNextTestCase();
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.doTests failure:" + err.message);
+        }
+    },
+
+    showSuitesStats: function()
+    {
+        try
+        {
+            jsPrint("============ Test suites:");
+            for(var i in this.testSuiteStats)
+            {
+                jsPrint(i + " - " + this.testSuiteStats[i].passed + " passed, " + this.testSuiteStats[i].failed + " failed," + "   asserts: " + this.testSuiteStats[i].assertsOK + " passed, " + this.testSuiteStats[i].assertsErr + " failed"); }
+        }
+        catch(err)
+        {
+            jsPrint("   TestEngine.showSuitesStats failure:" + err.message);
+        }
+    },
+
+    doNextTestCase: function()
+    {
+        try
+        {
+            if( TestEngine.stepsArray !== null || (TestEngine.callbackMutex > 0))
+            {
+                setTimeout( TestEngine.doNextTestCase, 100 );
+                return;
+            }
+
+            if(TestEngine.currentTestCase)
+            {
+                TestEngine.endTestCase(TestEngine.testList[TestEngine.currentTestCase-1]);
+            }
+
+            if( TestEngine.testList.length == TestEngine.currentTestCase )
+            {
+                if (widget.__test) {
+                    widget.__test.outputResults();
+                }
+                jsPrint("============");
+                jsPrint(TestEngine.finalLog);
+                TestEngine.showSuitesStats();
+                jsPrint("============ Summary:");
+                jsPrint("Test cases all: " + TestEngine.testList.length);
+                jsPrint("Test cases passed: " + TestEngine.testCasesPassedCount);
+                jsPrint("Test cases failed: " + TestEngine.testCasesFailedCount);
+                jsPrint("Asserts passed: " + TestEngine.countAllPassed);
+                jsPrint("Asserts failed: " + TestEngine.countAllFailed);
+                if (isVerbose()) {
+                    jsPrint("============ Failing test cases:");
+                    for (i = 0; i < TestEngine.testCasesFailed.length; ++i) {
+                        jsPrint(TestEngine.testCasesFailed[i]);
+                    }
+                }
+                TestEngine.summaryRenderer.render(TestEngine);
+
+                if(typeof TestEngine.finalCallback != "undefined")
+                {
+                    jsPrint("Registering final callback");
+                    TestEngine.summaryRenderer.render(TestEngine);
+                    setTimeout(TestEngine.finalCallback, 4000);
+                } else {
+                    jsPrint("Final callback was not registered.");
+                }
+                return;
+            }
+
+            var i = TestEngine.currentTestCase++;
+            try
+            {
+                if (widget.__test) {
+                    if (TestEngine.currentTestSuiteName != TestEngine.testList[i].testSuite) {
+                        TestEngine.currentTestSuiteName = TestEngine.testList[i].testSuite;
+                        widget.__test.collectGroup(TestEngine.testList[i].testSuite);
+                    }
+                }
+                TestEngine.log("");
+                TestEngine.log("==== Test case: " + TestEngine.testList[i].testName);
+                TestEngine.startTestCase();
+                var testPrereq = true;
+                if (TestEngine.testList[i].testPrereq !== undefined)
+                {
+                    testPrereq = TestEngine.testList[i].testPrereq();
+                }
+                if (testPrereq)
+                {
+                    if(TestEngine.testList[i].enabled)
+                    {
+                        TestEngine.testList[i].testFunc();
+                    }
+                    else
+                    {
+                        TestEngine.logIgnored("Test disabled");
+                    }
+
+                }
+                else {
+                    TestEngine.logException
+                    ("Test case prerequisites unfulfilled.  Skipping it.");
+                }
+            }
+            catch(err)
+            {
+                TestEngine.countException++;
+                TestEngine.log("   Test case '" + TestEngine.testList[i].testName + "' failed:" + err.message);
+            }
+            setTimeout( TestEngine.doNextTestCase, 100 );
+        }
+        catch(err)
+        {
+            jsPrint("   TestEngine.doNextTestCase failure:" + err.message);
+        }
+    }
+};
+
+function isUndefined(val)
+{
+    if (typeof val == "undefined") {
+        return true;
+    }
+    return false;
+}
+function isNull(val)
+{
+    return val === null;
+}
+function isString(val) {
+    if (typeof val == typeof "") {
+        return true;
+    }
+    return false;
+}
+function isNumber(val) {
+    if (typeof val == typeof 0) {
+        return true
+    }
+    return false;
+}
+function isDate(val) {
+    return (val instanceof Date);
+}
+function isFunction(val) {
+    return (typeof(val) == 'function');
+}
+function isBoolean(val) {
+    if (typeof val == typeof true) {
+        return true
+    }
+    return false;
+}
+function isArray(val) {
+    return (val instanceof Array);
+}
+function isObject(val) {
+    return (val instanceof Object);
+}
+
+function isVerbose() {
+    return ((typeof(VERBOSE) != "undefined") && (VERBOSE === 1));
+}
+
+/**
+ * Tests results logger.
+ */
+function HTMLTestResultLogger(sinkId) {
+
+  /**
+   * Logs a message.
+   * @param message Message to log.
+   * @param status Status of the message (PASSED, FAILED, EXCEPTION).
+   *               By default status is set to PASSED.
+   */
+  this.log = function(message, status) {
+    if (arguments.length < 2) throw "Not enough number of arguments.";
+    $(sink).append(createLogEntry(message, status));
+  }
+
+  /**
+   * Helper functions.
+   */
+  this.logPass = function(message) {
+    if (arguments.length < 1) throw "Not enough number of arguments.";
+    this.log(message, HTMLTestResultLogger.PASSED);
+  }
+
+  this.logFail = function(message) {
+    if (arguments.length < 1) throw "Not enough number of arguments.";
+    this.log(message, HTMLTestResultLogger.FAILED);
+  }
+
+  $(document).ready(function() {
+    sink = document.getElementById(sinkId);
+    if (null === sink) throw "Summary element unavailable.";
+  });
+
+  var createLogEntry = function(message, status) {
+    var entry = '<div class="entry ' + status + '">';
+    entry +=    message.toString();
+    entry +=    '</div>';
+    return entry;
+  }
+
+  var id = sinkId;
+  var sink = null;
+}
+
+HTMLTestResultLogger.PASSED = "passed";
+HTMLTestResultLogger.FAILED = "failed";
+HTMLTestResultLogger.EXCEPTION = "exception";
+
+
+/**
+ * Tests summary renderer.
+ */
+function HTMLTestSummaryRenderer(summaryId) {
+
+  this.render = function(engine) {
+    if (arguments.length < 1) throw "Not enough arguments.";
+
+    $('#_summary_numberOfRunTests').text(engine.currentTestCase);
+    $('#_summary_numberOfAllTests').text(engine.testList.length);
+    $('#_summary_numberOfPassedTests').text(engine.testCasesPassedCount);
+    $('#_summary_numberOfPassedAsserts').text(engine.countAllPassed);
+    $('#_summary_numberOfFailedTests').text(engine.testCasesFailedCount);
+    $('#_summary_numberOfFailedAsserts').text(engine.countAllFailed);
+    for(var suiteName in engine.testSuiteStats) {
+      if (!isSuiteStarted(engine.testSuiteStats[suiteName])) continue;
+      renderSuite(suiteName, engine.testSuiteStats[suiteName]);
+    }
+  }
+
+  $(document).ready(function() {
+    summary = document.getElementById(summaryId);
+    if (null === summary) {
+      throw "Summary element unavailable.";
+    }
+    setupSummary(summary);
+  });
+
+  var isSuiteStarted = function(stats) {
+    return (stats.passed + stats.failed != 0);
+  }
+
+  var renderSuite = function(name, stats) {
+    var elementId = '_summary_suite_' + name;
+    var element = document.getElementById(elementId);
+    if (null === element) {
+      element = $('<div id="' + elementId + '">' + name + ': '+ '<span name="stats"></span></div>');
+      $(summary).append(element);
+    }
+    var elementStats = $(element).children('span[name="stats"]');
+    elementStats.text(stats.passed + '(' + stats.assertsOK + ')' + ' passed, ' +
+                      stats.failed + '(' + stats.assertsErr + ')' + ' failed');
+  }
+
+  var setupSummary = function(summary) {
+    var run  = '<div>Run: <span id="_summary_numberOfRunTests">0</span>';
+        run += ' of <span id="_summary_numberOfAllTests">0</span></div>';
+    var current = '<div>Current: <span id="_summary_currentTest">0</span></div>';
+    var passed  = '<div>Passed: <span id="_summary_numberOfPassedTests">0</span>';
+        passed += '(<span id="_summary_numberOfPassedAsserts">0</span>)</div>';
+    var failed  = '<div>Failed: <span id="_summary_numberOfFailedTests">0</span>';
+        failed += '(<span id="_summary_numberOfFailedAsserts">0</span>)</div>';
+    $(summary).append(run).append(passed).append(failed);
+  }
+
+  var id = summaryId;
+  var summary = null;
+}
+
diff --git a/tests/geolocation_security/geolocationSecurityTest/js/WAC2.0/TestGeolocation.js b/tests/geolocation_security/geolocationSecurityTest/js/WAC2.0/TestGeolocation.js
new file mode 100644 (file)
index 0000000..418ef3e
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+function presenceTest()
+{
+    TestEngine.test("Checking checking", true);
+    TestEngine.test("Checking Geolocation object", navigator.geolocation);
+
+    TestEngine.test("Checking function getCurrentPosition",
+        isFunction(navigator.geolocation.getCurrentPosition));
+}
+
+function accessTest()
+{
+    try {
+        jsPrint("DEBUG POINT 0");
+        var callbackObject = TestEngine.registerCallback("getCurrentPositionCallback",
+                                                         localSuccessCallback,
+                                                         localErrorCallback);
+        jsPrint("DEBUG POINT 1");
+        navigator.geolocation.getCurrentPosition(
+            callbackObject.successCallback,
+            callbackObject.errorCallback);
+        jsPrint("DEBUG POINT 2");
+    } catch (error) {
+        jsPrint("DEBUG POINT 3");
+        TestEngine.logErr("Error in: navigator.geolocation.getCurrentPosition");
+    }
+    jsPrint("DEBUG POINT 4");
+}
+
+TestEngine.setTestSuiteName("[WAC2.0][Geolocation]", 30*1000); // 30 seconds
+TestEngine.addTest(true, presenceTest, "[WAC2.0][Geolocation] Geolocation prenence test");
+TestEngine.addTest(true, accessTest, "[WAC2.0][Geolocation] Access test");
+TestEngine.setFinalCallback(function(){ jsPrint("closing window"); window.close(); });
diff --git a/tests/geolocation_security/geolocationSecurityTest/js/WAC2.0/TestGeolocationCallback1.js b/tests/geolocation_security/geolocationSecurityTest/js/WAC2.0/TestGeolocationCallback1.js
new file mode 100644 (file)
index 0000000..43f0902
--- /dev/null
@@ -0,0 +1,9 @@
+function localSuccessCallback(position){
+    jsPrint("Success callback");
+    TestEngine.test("Access granted.", true);
+}
+
+function localErrorCallback(error){
+    jsPrint("Error callback");
+    TestEngine.test("Access failed.", false);
+}
diff --git a/tests/geolocation_security/geolocationSecurityTest/js/WAC2.0/TestGeolocationCallback2.js b/tests/geolocation_security/geolocationSecurityTest/js/WAC2.0/TestGeolocationCallback2.js
new file mode 100644 (file)
index 0000000..5d62822
--- /dev/null
@@ -0,0 +1,9 @@
+function localSuccessCallback(position){
+    jsPrint("Success callback");
+    TestEngine.test("Access granted.", false);
+}
+
+function localErrorCallback(error){
+    jsPrint("Error callback");
+    TestEngine.test("Access failed.", true);
+}
diff --git a/tests/geolocation_security/geolocationSecurityTest/js/include.js b/tests/geolocation_security/geolocationSecurityTest/js/include.js
new file mode 100644 (file)
index 0000000..75c02d1
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestGeolocationCallback.js")
+IncludeJavaScript("js/WAC2.0/TestGeolocation.js")
diff --git a/tests/geolocation_security/geolocationSecurityTest/js/jquery.js b/tests/geolocation_security/geolocationSecurityTest/js/jquery.js
new file mode 100644 (file)
index 0000000..381ebfe
--- /dev/null
@@ -0,0 +1,40 @@
+/*!
+ * Copyright (C) 2011, John Resig
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the "Software"), to deal in
+ * the Software without restriction, including without limitation the rights to
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is furnished to do
+ * so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+/*!
+ * jQuery JavaScript Library v1.7
+ * http://jquery.com/
+ *
+ * Copyright 2011, John Resig
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ * Copyright 2011, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ *
+ * Date: Thu Nov 3 16:18:21 2011 -0400
+ */
+
+(function(a,b){function cA(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cx(a){if(!cm[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cn||(cn=c.createElement("iframe"),cn.frameBorder=cn.width=cn.height=0),b.appendChild(cn);if(!co||!cn.createElement)co=(cn.contentWindow||cn.contentDocument).document,co.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),co.close();d=co.createElement(a),co.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cn)}cm[a]=e}return cm[a]}function cw(a,b){var c={};f.each(cs.concat.apply([],cs.slice(0,b)),function(){c[this]=a});return c}function cv(){ct=b}function cu(){setTimeout(cv,0);return ct=f.now()}function cl(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ck(){try{return new a.XMLHttpRequest}catch(b){}}function ce(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cd(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function cc(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bG.test(a)?d(a,e):cc(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)cc(a+"["+e+"]",b[e],c,d);else d(a,b)}function cb(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function ca(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bV,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=ca(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=ca(a,c,d,e,"*",g));return l}function b_(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bR),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bE(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bz:bA;if(d>0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bB(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function br(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bi,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bq(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bp(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bp)}function bp(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bo(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bn(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bm(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bl(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function X(a){var b=Y.split(" "),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function W(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(R.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(){return!0}function M(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function K(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(K,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z]|[0-9])/ig,x=/^-ms-/,y=function(a,b){return(b+"").toUpperCase()},z=d.userAgent,A,B,C,D=Object.prototype.toString,E=Object.prototype.hasOwnProperty,F=Array.prototype.push,G=Array.prototype.slice,H=String.prototype.trim,I=Array.prototype.indexOf,J={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=n.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7",length:0,size:function(){return this.length},toArray:function(){return G.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?F.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),B.add(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(G.apply(this,arguments),"slice",G.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:F,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;B.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!B){B=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",C,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",C),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&K()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return a!=null&&m.test(a)&&!isNaN(a)},type:function(a){return a==null?String(a):J[D.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!E.call(a,"constructor")&&!E.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||E.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(x,"ms-").replace(w,y)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:H?function(a){return a==null?"":H.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?F.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(I)return I.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=G.call(arguments,2),g=function(){return a.apply(c,f.concat(G.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=s.exec(a)||t.exec(a)||u.exec(a)||a.indexOf("compatible")<0&&v.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){J["[object "+b+"]"]=b.toLowerCase()}),A=e.uaMatch(z),A.browser&&(e.browser[A.browser]=!0,e.browser.version=A.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?C=function(){c.removeEventListener("DOMContentLoaded",C,!1),e.ready()}:c.attachEvent&&(C=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",C),e.ready())}),typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return e});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){return i.done.apply(i,arguments).fail.apply(i,arguments)},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var a=c.createElement("div"),b=c.documentElement,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;a.setAttribute("className","t"),a.innerHTML="   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/><nav></nav>",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,unknownElems:!!a.getElementsByTagName("nav").length,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",enctype:!!c.createElement("form").enctype,submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.lastChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},m&&f.extend(p,{position:"absolute",left:"-999px",top:"-999px"});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;f(function(){var a,b,d,e,g,h,i=1,j="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",l="visibility:hidden;border:0;",n="style='"+j+"border:5px solid #000;padding:0;'",p="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>";m=c.getElementsByTagName("body")[0];!m||(a=c.createElement("div"),a.style.cssText=l+"width:0;height:0;position:static;top:0;margin-top:"+i+"px",m.insertBefore(a,m.firstChild),o=c.createElement("div"),o.style.cssText=j+l,o.innerHTML=p,a.appendChild(o),b=o.firstChild,d=b.firstChild,g=b.nextSibling.firstChild.firstChild,h={doesNotAddBorder:d.offsetTop!==5,doesAddBorderForTableAndCells:g.offsetTop===5},d.style.position="fixed",d.style.top="20px",h.fixedPosition=d.offsetTop===20||d.offsetTop===15,d.style.position=d.style.top="",b.style.overflow="hidden",b.style.position="relative",h.subtractsBorderForOverflowNotVisible=d.offsetTop===-5,h.doesNotIncludeMarginInBodyOffset=m.offsetTop!==i,m.removeChild(a),o=a=null,f.extend(k,h))}),o.innerHTML="",n.removeChild(o),o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[f.expando]:a[f.expando]&&f.expando,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[f.expando]=n=++f.uuid:n=f.expando),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[f.expando]:f.expando;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)?b=b:b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" "));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[f.expando]:a.removeAttribute?a.removeAttribute(f.expando):a[f.expando]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];if(!arguments.length){if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}return b}e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!a||j===3||j===8||j===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g},removeAttr:function(a,b){var c,d,e,g,h=0;if(a.nodeType===1){d=(b||"").split(p),g=d.length;for(;h<g;h++)e=d[h].toLowerCase(),c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1)}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return b;h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/\.(.*)$/,A=/^(?:textarea|input|select)$/i,B=/\./g,C=/ /g,D=/[^\w\s.|`]/g,E=/^([^\.]*)?(?:\.(.+))?$/,F=/\bhover(\.\S+)?/,G=/^key/,H=/^(?:mouse|contextmenu)|click/,I=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,J=function(a){var b=I.exec(a);b&&
+(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},K=function(a,b){return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||a.id===b[2])&&(!b[3]||b[3].test(a.className))},L=function(a){return f.event.special.hover?a:a.replace(F,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=L(c).split(" ");for(k=0;k<c.length;k++){l=E.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,namespace:n.join(".")},p),g&&(o.quick=J(g),!o.quick&&f.expr.match.POS.test(g)&&(o.isPositional=!0)),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d){var e=f.hasData(a)&&f._data(a),g,h,i,j,k,l,m,n,o,p,q;if(!!e&&!!(m=e.events)){b=L(b||"").split(" ");for(g=0;g<b.length;g++){h=E.exec(b[g])||[],i=h[1],j=h[2];if(!i){j=j?"."+j:"";for(l in m)f.event.remove(a,l+j,c,d);return}n=f.event.special[i]||{},i=(d?n.delegateType:n.bindType)||i,p=m[i]||[],k=p.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;if(c||j||d||n.remove)for(l=0;l<p.length;l++){q=p[l];if(!c||c.guid===q.guid)if(!j||j.test(q.namespace))if(!d||d===q.selector||d==="**"&&q.selector)p.splice(l--,1),q.selector&&p.delegateCount--,n.remove&&n.remove.call(a,q)}else p.length=0;p.length===0&&k!==p.length&&((!n.teardown||n.teardown.call(a,j)===!1)&&f.removeEvent(a,i,e.handle),delete m[i])}f.isEmptyObject(m)&&(o=e.handle,o&&(o.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"",(g||!e)&&c.preventDefault();if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,n=null;for(m=e.parentNode;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length;l++){m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d);if(c.isPropagationStopped())break}c.type=h,c.isDefaultPrevented()||(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=(f.event.special[c.type]||{}).handle,j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click"))for(m=c.target;m!=this;m=m.parentNode||this){o={},q=[];for(k=0;k<e;k++)r=d[k],s=r.selector,t=o[s],r.isPositional?t=(t||(o[s]=f(s))).index(m)>=0:t===b&&(t=o[s]=r.quick?K(m,r.quick):f(m).is(s)),t&&q.push(r);q.length&&j.push({elem:m,matches:q})}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){p=j[k],c.currentTarget=p.elem;for(l=0;l<p.matches.length&&!c.isImmediatePropagationStopped();l++){r=p.matches[l];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=(i||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement wheelDelta".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},focus:{delegateType:"focusin",noBubble:!0},blur:{delegateType:"focusout",noBubble:!0},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?N:M):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=N;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=N;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=N,this.stopPropagation()},isDefaultPrevented:M,isPropagationStopped:M,isImmediatePropagationStopped:M},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]=f.event.special[b]={delegateType:b,bindType:b,handle:function(a){var b=this,c=a.relatedTarget,d=a.handleObj,e=d.selector,g,h;if(!c||d.origType===a.type||c!==b&&!f.contains(b,c))g=a.type,a.type=d.origType,h=d.handler.apply(this,arguments),a.type=g;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(A.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;A.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return A.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=M;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=M);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),G.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),H.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw"Syntax error, unrecognized expression: "+a};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var O=/Until$/,P=/^(?:parents|prevUntil|prevAll)/,Q=/,/,R=/^.[^:#\[\.,]*$/,S=Array.prototype.slice,T=f.expr.match.POS,U={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(W(this,a,!1),"not",a)},filter:function(a){return this.pushStack(W(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?T.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=T.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(V(c[0])||V(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var Y="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",Z=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,_=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,ba=/<([\w:]+)/,bb=/<tbody/i,bc=/<|&#?\w+;/,bd=/<(?:script|style)/i,be=/<(?:script|object|embed|option|style)/i,bf=new RegExp("<(?:"+Y.replace(" ","|")+")","i"),bg=/checked\s*(?:[^=]|=\s*.checked.)/i,bh=/\/(java|ecma)script/i,bi=/^\s*<!(?:\[CDATA\[|\-\-)/,bj={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bk=X(c);bj.optgroup=bj.option,bj.tbody=bj.tfoot=bj.colgroup=bj.caption=bj.thead,bj.th=bj.td,f.support.htmlSerialize||(bj._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){f(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after"
+,arguments);a.push.apply(a,f(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Z,""):null;if(typeof a=="string"&&!bd.test(a)&&(f.support.leadingWhitespace||!$.test(a))&&!bj[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(_,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bg.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bl(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,br)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!be.test(j)&&(f.support.checkClone||!bg.test(j))&&!f.support.unknownElems&&bf.test(j)&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bn(a,d),e=bo(a),g=bo(d);for(h=0;e[h];++h)g[h]&&bn(e[h],g[h])}if(b){bm(a,d);if(c){e=bo(a),g=bo(d);for(h=0;e[h];++h)bm(e[h],g[h])}}e=g=null;return d},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!bc.test(k))k=b.createTextNode(k);else{k=k.replace(_,"<$1></$2>");var l=(ba.exec(k)||["",""])[1].toLowerCase(),m=bj[l]||bj._default,n=m[0],o=b.createElement("div");b===c?bk.appendChild(o):X(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=bb.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&$.test(k)&&o.insertBefore(b.createTextNode($.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bq(k[i]);else bq(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bh.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bs=/alpha\([^)]*\)/i,bt=/opacity=([^)]*)/,bu=/([A-Z]|^ms)/g,bv=/^-?\d+(?:px)?$/i,bw=/^-?\d/,bx=/^([\-+])=([\-+.\de]+)/,by={position:"absolute",visibility:"hidden",display:"block"},bz=["Left","Right"],bA=["Top","Bottom"],bB,bC,bD;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bB(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bx.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bB)return bB(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bE(a,b,d);f.swap(a,by,function(){e=bE(a,b,d)});return e}},set:function(a,b){if(!bv.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bt.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bs,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bs.test(g)?g.replace(bs,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bB(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bC=function(a,c){var d,e,g;c=c.replace(bu,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bD=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bv.test(f)&&bw.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bB=bC||bD,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bF=/%20/g,bG=/\[\]$/,bH=/\r?\n/g,bI=/#.*$/,bJ=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bK=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bL=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bM=/^(?:GET|HEAD)$/,bN=/^\/\//,bO=/\?/,bP=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bQ=/^(?:select|textarea)/i,bR=/\s+/,bS=/([?&])_=[^&]*/,bT=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bU=f.fn.load,bV={},bW={},bX,bY,bZ=["*/"]+["*"];try{bX=e.href}catch(b$){bX=c.createElement("a"),bX.href="",bX=bX.href}bY=bT.exec(bX.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bU)return bU.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bP,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bQ.test(this.nodeName)||bK.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bH,"\r\n")}}):{name:b.name,value:c.replace(bH,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?cb(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),cb(a,b);return a},ajaxSettings:{url:bX,isLocal:bL.test(bY[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bZ},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:b_(bV),ajaxTransport:b_(bW),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cd(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=ce(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bJ.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bI,"").replace(bN,bY[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bR),d.crossDomain==null&&(r=bT.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bY[1]&&r[2]==bY[2]&&(r[3]||(r[1]==="http:"?80:443))==(bY[3]||(bY[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),ca(bV,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bM.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bO.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bS,"$1_="+x);d.url=y+(y===d.url?(bO.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bZ+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=ca(bW,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){s<2?w(-1,z):f.error(z)}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)cc(g,a[g],c,e);return d.join("&").replace(bF,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cf=f.now(),cg=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cf++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cg.test(b.url)||e&&cg.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cg,l),b.url===j&&(e&&(k=k.replace(cg,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ch=a.ActiveXObject?function(){for(var a in cj)cj[a](0,1)}:!1,ci=0,cj;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ck()||cl()}:ck,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ch&&delete cj[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++ci,ch&&(cj||(cj={},f(a).unload(ch)),cj[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cm={},cn,co,cp=/^(?:toggle|show|hide)$/,cq=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cr,cs=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],ct;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cw("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cx(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cw("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cw("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cx(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cp.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=cq.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cw("show",1),slideUp:cw("hide",1),slideToggle:cw("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=ct||cu(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cr&&(cr=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=ct||cu(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cr),cr=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now))}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cy=/^t(?:able|d|h)$/i,cz=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cA(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cy.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cz.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cz.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cA(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cA(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window);
diff --git a/tests/geolocation_security/wrt-tests-security-geolocation.sh b/tests/geolocation_security/wrt-tests-security-geolocation.sh
new file mode 100755 (executable)
index 0000000..f0dbe0e
--- /dev/null
@@ -0,0 +1,82 @@
+#/bin/sh
+
+TEST_RESULT_DIR=
+TEST_TYPE="text"
+
+while getopts "o:d:" opts
+do
+    case "$opts" in
+        d)  echo "Output directory: $OPTARG"
+            TEST_RESULT_DIR="$OPTARG" ;;
+        o)  echo "Output type: $OPTARG"
+            TEST_TYPE="$OPTARG" ;;
+        [?])echo "Usage $0 [-o output_type] [-d output_directory]"
+            exit 1;;
+    esac
+done
+
+result=`rpm -qa | grep wrt-extra`
+if [ -z "$result" ]; then
+    echo "You must install wrt-extra before run this script";
+    exit;
+fi
+
+export DPL_USE_OLD_STYLE_LOGS=0
+export DPL_TEST_OUTPUT="$TEST_TYPE"
+
+wrt_reset_all.sh
+if [ -e /usr/etc/ace/WAC2.0Policy.back ]; then
+    echo "Policy backup already exists";
+else
+    mv /usr/etc/ace/WAC2.0Policy.xml /usr/etc/ace/WAC2.0Policy.back
+fi
+
+echo "Set up policy file"
+cp /usr/etc/ace/GeolocationPolicyTest1 /usr/etc/ace/WAC2.0Policy.xml
+
+echo "Reset policy settings in daemon"
+wrt_security_change_policy.sh
+
+function move_result(){
+    source=`pwd`
+    echo "Function move_resutl. Source: $source"
+    if [ "x$TEST_RESULT_DIR" = "x" ]; then
+        return
+    fi
+
+    if [ "x$TEST_TYPE" != "x" ]; then
+        echo "Move: mv results.xml $TEST_RESULT_DIR/$1.$TEST_TYPE"
+        mv results.xml "$TEST_RESULT_DIR/$1.$TEST_TYPE"
+    fi
+}
+
+function run_widget(){
+    uid=`echo $1 | awk -F ": " '{print $2}'`
+    if echo $uid | egrep -q '^[0-9]+$'; then
+        echo "Second widget id: $uid"
+        DPL_TEST_OUTPUT=text wrt-client -l $uid
+    else
+        echo "Result: $1"
+    fi
+    move_result "geolocation_$1"
+}
+
+echo "Widget installation"
+result1=`wrt-installer -if /opt/apps/widget/tests/geolocation/geolocationSecurityTest1.wgt`
+result2=`wrt-installer -if /opt/apps/widget/tests/geolocation/geolocationSecurityTest2.wgt`
+
+run_widget "$result1"
+
+echo "Set up policy file"
+cp /usr/etc/ace/GeolocationPolicyTest2 /usr/etc/WAC2.0Policy.xml
+echo "Reset policy setting in daemon."
+wrt_security_change_policy.sh
+
+run_widget "$result2"
+
+echo "Restore original policy"
+cp /usr/etc/ace/WAC2.0Policy.back /usr/etc/ace/WAC2.0Policy.xml
+echo "Reset policy settings in daemon"
+wrt_security_change_policy.sh
+
+
diff --git a/tests/security-tests.sh b/tests/security-tests.sh
new file mode 100755 (executable)
index 0000000..c3da82f
--- /dev/null
@@ -0,0 +1,143 @@
+#!/bin/sh
+
+#####################################################################
+# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#####################################################################
+
+#####################################################################
+#   author: pawel.polawski@partner.samsung.com
+#####################################################################
+
+#testing internet access and date on the target
+error(){
+    echo "[ERROR]" $1
+    exit 1
+}
+
+check_network_access(){
+  echo "--- Checking for network access..."
+  ping -c 2 www.google.com > /dev/null || error 'Network not accessible'
+  echo 'Network access OK'
+}
+
+check_date(){
+  echo "--- Checkig date..."
+  date
+  openssl verify -CAfile /opt/apps/widget/tests/vcore_certs/cacert.pem   /opt/apps/widget/tests/vcore_certs/respcert.pem 2>/dev/null | grep OK 1>/dev/null || error 'Date not set properly'
+  echo 'Date OK'
+}
+
+kill_daemons(){
+    #minimum time after kill should be at lest 2 seconds
+    echo "--- Killing daemons"
+    wrt_security_create_clean_db.sh
+    pkill -9 security-ser
+    sleep 3
+    pkill -9 wrt-security
+    sleep 3
+    echo "--- Done"
+}
+
+start_daemons(){
+    echo "--- Starting daemons"
+    sleep 1
+    security-server &
+    sleep 1
+    wrt-security-daemon &
+    sleep 1
+    echo "--- Done"
+}
+
+
+echo "### Starting tests ######################################################"
+
+case $1 in
+
+"ace")
+    echo "========================================================================="
+    echo "ACE"
+    echo
+    #environment setup
+    cp /usr/etc/ace/WAC2.0Policy.xml /usr/etc/ace/WAC2.0Policy.xml.bk
+    cp /usr/etc/ace/TizenPolicy.xml /usr/etc/ace/TizenPolicy.xml.bk
+    cp /usr/etc/ace/WAC2.0Policy-test.xml /usr/etc/ace/WAC2.0Policy.xml
+    cp /usr/etc/ace/TizenPolicy-test.xml /usr/etc/ace/TizenPolicy.xml
+    kill_daemons
+    #test binary execution
+    wrt-tests-ace $2 $3
+    ;;
+
+"ace-client")
+    echo "========================================================================="
+    echo "ACE-CLIENT"
+    echo
+    #environment setup
+    cp /usr/etc/ace/WAC2.0Policy.xml.bk /usr/etc/ace/WAC2.0Policy.xml
+    cp /usr/etc/ace/TizenPolicy.xml.bk /usr/etc/ace/TizenPolicy.xml
+    kill_daemons
+    #test binary execution
+    wrt-tests-ace-client $2 $3
+    ;;
+
+"ace-settings")
+    echo "========================================================================="
+    echo "ACE-SETTINGS"
+    echo
+    #environment setup
+    kill_daemons
+    #test binary execution
+    wrt-tests-ace-settings $2 $3
+    ;;
+
+"ace-install")
+    echo "========================================================================="
+    echo "ACE-INSTALL"
+    echo
+    #environment setup
+    cp /usr/etc/ace/WAC2.0Policy.xml /usr/etc/ace/WAC2.0Policy.xml.bk
+    cp /usr/etc/ace/ace-install-api-demo-policy.xml /usr/etc/ace/WAC2.0Policy.xml
+    wrt_security_change_policy.sh
+    kill_daemons
+    #test binary execution
+    wrt-tests-ace-install $2 $3
+    ;;
+
+"security-daemon")
+    echo "========================================================================="
+    echo "SECURITY-DAEMON"
+    echo
+    #environment setup
+    cp /usr/etc/ace/WAC2.0Policy.xml.bk /usr/etc/ace/WAC2.0Policy.xml
+    cp /usr/etc/ace/WAC2.0Policy.xml /usr/etc/ace/WAC2.0Policy.xml.bk
+    cp /usr/etc/ace/ipc-tests-demo.xml /usr/etc/ace/WAC2.0Policy.xml
+    wrt_security_change_policy.sh
+    kill_daemons
+    #test binary execution
+    wrt-tests-security-daemon $2 $3
+    ;;
+
+*)
+    echo "Correct using:"
+    echo "    security_test.sh <module> <args_for_module>"
+    echo
+    echo "modules: ace, ace-client, ace-settings, ace-install, security-daemon"
+    ;;
+
+esac
+
+#clean up
+kill_daemons
+
+echo "### Tests done ##########################################################"
diff --git a/tests/security_daemon_tests/CMakeLists.txt b/tests/security_daemon_tests/CMakeLists.txt
new file mode 100644 (file)
index 0000000..440254c
--- /dev/null
@@ -0,0 +1,55 @@
+#
+#Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#   Licensed under the Apache License, Version 2.0 (the "License");
+#   you may not use this file except in compliance with the License.
+#   You may obtain a copy of the License at
+#
+#       http://www.apache.org/licenses/LICENSE-2.0
+#
+#   Unless required by applicable law or agreed to in writing, software
+#   distributed under the License is distributed on an "AS IS" BASIS,
+#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#   See the License for the specific language governing permissions and
+#   limitations under the License.
+#
+# @file        CMakeLists.txt
+# @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+# @brief
+#
+
+SET(TARGET_SEC_DAEMON_TESTS "wrt-tests-security-daemon")
+SET(SEC_DAEMON_SOURCES
+    ${COMMUNICATION_CLIENT_SOURCES}
+    ace_ipc_test_cases.cpp
+    service_test_cases.cpp
+    fake_service.cpp
+    ${PROJECT_SOURCE_DIR}/src/daemon/security_daemon.cpp
+    main.cpp
+   )
+PKG_CHECK_MODULES(SEC_DAEMON_TESTS_PKGS
+    dbus-1
+    dpl-test-efl
+    dpl-dbus-efl
+    dpl-utils-efl
+    REQUIRED)
+
+INCLUDE_DIRECTORIES(
+    ${SEC_DAEMON_TESTS_PKGS_INCLUDE_DIRS}
+    ${COMMUNICATION_CLIENT_INCLUDES}
+    ${PROJECT_SOURCE_DIR}/ace/include/
+    ${PROJECT_SOURCE_DIR}/src/daemon
+    ${PROJECT_SOURCE_DIR}/tests/security_daemon_tests
+    ${PROJECT_SOURCE_DIR}/tests/ace_install
+    )
+
+LINK_DIRECTORIES(${SEC_DAEMON_TESTS_PKGS_LIBRARY_DIRS})
+
+ADD_EXECUTABLE(${TARGET_SEC_DAEMON_TESTS} ${SEC_DAEMON_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_SEC_DAEMON_TESTS}
+    ${SEC_DAEMON_TESTS_PKGS_LIBRARIES}
+    ${TARGET_ACE_LIB})
+
+INSTALL(TARGETS ${TARGET_SEC_DAEMON_TESTS} DESTINATION /usr/bin)
+INSTALL(FILES "ipc-tests-demo.xml" DESTINATION /usr/etc/ace)
diff --git a/tests/security_daemon_tests/HOWTO.txt b/tests/security_daemon_tests/HOWTO.txt
new file mode 100644 (file)
index 0000000..c47ec1a
--- /dev/null
@@ -0,0 +1 @@
+Is required to install '''ipc-tests-demo.xml''' ACE policy file and restart security daemon before executing this test suite.
diff --git a/tests/security_daemon_tests/ace_ipc_test_cases.cpp b/tests/security_daemon_tests/ace_ipc_test_cases.cpp
new file mode 100644 (file)
index 0000000..d07a57f
--- /dev/null
@@ -0,0 +1,386 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+#include <dpl/assert.h>
+#include <dpl/test/test_runner.h>
+#include <ace/PolicyResult.h>
+#include <ace-dao-ro/PromptModel.h>
+#include <ace-dao-ro/PromptModel.h>
+#include "SecurityCommunicationClient.h"
+#include <widget_installer.h>
+
+#include <vector>
+#include <string>
+#include <memory>
+
+using namespace DPL;
+
+namespace {
+
+const std::string ACE_INTERFACE_NAME =
+    "org.tizen.AceCheckAccessInterface";
+const std::string ACE_CHECK_ACCESS_METHOD = "check_access";
+
+const std::string POPUP_INTERFACE_NAME =
+    "org.tizen.PopupResponse";
+const std::string  VALIDATION_METHOD = "validate";
+
+}
+
+class AceClientStub
+{
+  public:
+
+    PolicyResult callCheckAccess(int handle,
+                                 const std::string& subjectId,
+                                 const std::string& resourceId,
+                                 const std::vector<std::string> keys,
+                                 const std::vector<std::string> values)
+    {
+        Assert(!!m_aceCommunicationClient);
+        int serialized = 0;
+        std::string sessionId = "fakeSession";
+        m_aceCommunicationClient->call(ACE_CHECK_ACCESS_METHOD,
+                              handle,
+                              subjectId,
+                              resourceId,
+                              keys,
+                              values,
+                              sessionId,
+                              &serialized);
+        PolicyResult policyResult = PolicyResult::deserialize(serialized);
+        return policyResult;
+    }
+
+    bool callPopupAnswer(bool allowed,
+                         int serializedValidity,
+                         int handle,
+                         const std::string& subjectId,
+                         const std::string& resourceId,
+                         const std::vector<std::string> keys,
+                         const std::vector<std::string> values,
+                         const std::string& session)
+    {
+        Assert(!!m_popupCommunicationClient);
+        bool status = false;
+        m_popupCommunicationClient->call(VALIDATION_METHOD,
+                                allowed,
+                                serializedValidity,
+                                handle,
+                                subjectId,
+                                resourceId,
+                                keys,
+                                values,
+                                session,
+                                &status);
+        return status;
+    }
+
+    static AceClientStub& getInstance();
+
+  private:
+    AceClientStub() :
+        m_aceCommunicationClient(new WrtSecurity::Communication::Client(ACE_INTERFACE_NAME)),
+        m_popupCommunicationClient(new WrtSecurity::Communication::Client(POPUP_INTERFACE_NAME))
+    {
+    }
+
+    ~AceClientStub() { }
+
+    std::unique_ptr<WrtSecurity::Communication::Client> m_aceCommunicationClient;
+    std::unique_ptr<WrtSecurity::Communication::Client> m_popupCommunicationClient;
+};
+
+AceClientStub& AceClientStub::getInstance()
+{
+    static AceClientStub instance;
+    return instance;
+}
+
+RUNNER_TEST_GROUP_INIT(ace)
+
+/* 
+ * author:      ---
+ * test:        Policy evaluation by security server.
+ * description: Prepared policy is passed to ACE and evaluation result is checked.
+ * expect:      Evaluation effect match assumptions, result should be PolicyEffect::PROMPT_ONESHOT.
+ */
+RUNNER_TEST(policy1)
+{
+    std::vector<std::string> names;
+    std::vector<std::string> values;
+    std::string subjectId = "resource_id_prompt_oneshot";
+    std::string resourceId = subjectId;
+    WidgetHandle widgetHandle = InstallerMockup::registerWidget();
+    auto policy = AceClientStub::getInstance().callCheckAccess(
+        widgetHandle,
+        subjectId,
+        resourceId,
+        names,
+        values);
+    RUNNER_ASSERT(!!policy.getEffect());
+    RUNNER_ASSERT(*policy.getEffect() == PolicyEffect::PROMPT_ONESHOT);
+}
+
+/* 
+ * author:      ---
+ * test:        Policy evaluation by security server.
+ * description: Prepared policy is passed to ACE and evaluation result is checked.
+ * expect:      Evaluation effect match assumptions, result should be PolicyEffect::PROMPT_BLANKET.
+ */
+RUNNER_TEST(policy2)
+{
+    std::vector<std::string> names;
+    std::vector<std::string> values;
+    std::string subjectId = "resource_id_prompt_blanket";
+    std::string resourceId = subjectId;
+    WidgetHandle widgetHandle = InstallerMockup::registerWidget();
+    auto policy = AceClientStub::getInstance().callCheckAccess(widgetHandle,
+                                                               subjectId,
+                                                               resourceId,
+                                                               names,
+                                                               values);
+    RUNNER_ASSERT(!!policy.getEffect());
+    RUNNER_ASSERT(*policy.getEffect() == PolicyEffect::PROMPT_BLANKET);
+}
+
+/* 
+ * author:      ---
+ * test:        Policy evaluation by security server.
+ * description: Prepared policy is passed to ACE and evaluation result is checked.
+ * expect:      Evaluation effect match assumptions, result should be PolicyEffect::PROMPT_SESSION.
+ */
+RUNNER_TEST(policy3)
+{
+    std::vector<std::string> names;
+    std::vector<std::string> values;
+    std::string subjectId = "resource_id_prompt_session";
+    std::string resourceId = subjectId;
+    WidgetHandle widgetHandle = InstallerMockup::registerWidget();
+    auto policy = AceClientStub::getInstance().callCheckAccess(widgetHandle,
+                                                               subjectId,
+                                                               resourceId,
+                                                               names,
+                                                               values);
+    RUNNER_ASSERT(!!policy.getEffect());
+    RUNNER_ASSERT(*policy.getEffect() == PolicyEffect::PROMPT_SESSION);
+}
+
+/* 
+ * author:      ---
+ * test:        Policy evaluation by security server.
+ * description: Prepared policy is passed to ACE and evaluation result is checked.
+ * expect:      Evaluation effect match assumptions, result should be PolicyEffect::PERMIT.
+ */
+RUNNER_TEST(policy4)
+{
+    std::vector<std::string> names;
+    std::vector<std::string> values;
+    std::string subjectId = "resource_id_permit";
+    std::string resourceId = subjectId;
+    WidgetHandle widgetHandle = InstallerMockup::registerWidget();
+    auto policy = AceClientStub::getInstance().callCheckAccess(widgetHandle,
+                                                               subjectId,
+                                                               resourceId,
+                                                               names,
+                                                               values);
+    RUNNER_ASSERT(!!policy.getEffect());
+    RUNNER_ASSERT(*policy.getEffect() == PolicyEffect::PERMIT);
+}
+
+/* 
+ * author:      ---
+ * test:        Policy evaluation by security server.
+ * description: Prepared policy is passed to ACE and evaluation result is checked.
+ * expect:      Evaluation effect match assumptions, result should be PolicyEffect::DENY.
+ */
+RUNNER_TEST(policy5)
+{
+    std::vector<std::string> names;
+    std::vector<std::string> values;
+    std::string subjectId = "resource_id_deny";
+    std::string resourceId = subjectId;
+    WidgetHandle widgetHandle = InstallerMockup::registerWidget();
+    auto policy = AceClientStub::getInstance().callCheckAccess(widgetHandle,
+                                                               subjectId,
+                                                               resourceId,
+                                                               names,
+                                                               values);
+    RUNNER_ASSERT(!!policy.getEffect());
+    RUNNER_ASSERT(*policy.getEffect() == PolicyEffect::DENY);
+}
+
+/* 
+ * author:      ---
+ * test:        Policy evaluation by security server.
+ * description: Prepared policy is passed to ACE and evaluation result is checked.
+ *              Next popup asking about accesses is passed to user.
+ * expect:      Evaluation effect match assumptions, result should be PolicyEffect::PROMPT_ONESHOT.
+ *              Popup contains correct evaluation results.
+ */
+RUNNER_TEST(popup_test_after_policy1)
+{
+    std::vector<std::string> names;
+    std::vector<std::string> values;
+    std::string resourceId = "resource_id_prompt_oneshot";
+    std::string subjectId = resourceId;
+    WidgetHandle widgetHandle = InstallerMockup::registerWidget();
+    auto policy = AceClientStub::getInstance().callCheckAccess(widgetHandle,
+                                                               subjectId,
+                                                               resourceId,
+                                                               names,
+                                                               values);
+    RUNNER_ASSERT(!!policy.getEffect());
+    RUNNER_ASSERT(*policy.getEffect() == PolicyEffect::PROMPT_ONESHOT);
+
+    int validity = static_cast<int>(Prompt::Validity::ONCE);
+    auto status = AceClientStub::getInstance().callPopupAnswer(true,
+                                                               validity,
+                                                               widgetHandle,
+                                                               subjectId,
+                                                               resourceId,
+                                                               names,
+                                                               values,
+                                                               "");
+    RUNNER_ASSERT(status);
+    LogDebug("1: " << status);
+    status = AceClientStub::getInstance().callPopupAnswer(false,
+                                                          validity,
+                                                          widgetHandle,
+                                                          subjectId,
+                                                          resourceId,
+                                                          names,
+                                                          values,
+                                                          "");
+    RUNNER_ASSERT(!status);
+    status = AceClientStub::getInstance().callPopupAnswer(true,
+                                                          validity,
+                                                          widgetHandle,
+                                                          subjectId,
+                                                          resourceId,
+                                                          names,
+                                                          values,
+                                                          "");
+    RUNNER_ASSERT(status);
+}
+
+/* 
+ * author:      ---
+ * test:        Policy evaluation by security server.
+ * description: Prepared policy is passed to ACE and evaluation result is checked.
+ *              Next popup asking about accesses is passed to user.
+ * expect:      Evaluation effect match assumptions, result should be PolicyEffect::PROMPT_BLANKET.
+ *              Popup contains correct evaluation results.
+ */
+RUNNER_TEST(popup_test_after_policy2)
+{
+    std::vector<std::string> names;
+    std::vector<std::string> values;
+    std::string resourceId = "resource_id_prompt_blanket";
+    std::string subjectId = resourceId;
+    WidgetHandle widgetHandle = InstallerMockup::registerWidget();
+    auto policy = AceClientStub::getInstance().callCheckAccess(widgetHandle,
+                                                               subjectId,
+                                                               resourceId,
+                                                               names,
+                                                               values);
+    RUNNER_ASSERT(!!policy.getEffect());
+    RUNNER_ASSERT(*policy.getEffect() == PolicyEffect::PROMPT_BLANKET);
+
+    int validity = static_cast<int>(Prompt::Validity::ALWAYS);
+    auto status = AceClientStub::getInstance().callPopupAnswer(true,
+                                                               validity,
+                                                               widgetHandle,
+                                                               subjectId,
+                                                               resourceId,
+                                                               names,
+                                                               values,
+                                                               "");
+    RUNNER_ASSERT(status);
+    LogDebug("1: " << status);
+    status = AceClientStub::getInstance().callPopupAnswer(false,
+                                                          validity,
+                                                          widgetHandle,
+                                                          subjectId,
+                                                          resourceId,
+                                                          names,
+                                                          values,
+                                                          "");
+    RUNNER_ASSERT(!status);
+    status = AceClientStub::getInstance().callPopupAnswer(true,
+                                                          validity,
+                                                          widgetHandle,
+                                                          subjectId,
+                                                          resourceId,
+                                                          names,
+                                                          values,
+                                                          "");
+    RUNNER_ASSERT(status);
+}
+
+/* 
+ * author:      ---
+ * test:        Policy evaluation by security server.
+ * description: Prepared policy is passed to ACE and evaluation result is checked.
+ *              Next popup asking about accesses is passed to user.
+ * expect:      Evaluation effect match assumptions, result should be Prompt::Validity::SESSION.
+ *              Popup contains correct evaluation results.
+ */
+RUNNER_TEST(popup_test_after_policy3)
+{
+    std::vector<std::string> names;
+    std::vector<std::string> values;
+    std::string resourceId = "resource_id_prompt_session";
+    std::string subjectId = resourceId;
+    WidgetHandle widgetHandle = InstallerMockup::registerWidget();
+    auto policy = AceClientStub::getInstance().callCheckAccess(widgetHandle,
+                                                               subjectId,
+                                                               resourceId,
+                                                               names,
+                                                               values);
+    RUNNER_ASSERT(!!policy.getEffect());
+    RUNNER_ASSERT(*policy.getEffect() == PolicyEffect::PROMPT_SESSION);
+
+    int validity = static_cast<int>(Prompt::Validity::SESSION);
+    auto status = AceClientStub::getInstance().callPopupAnswer(true,
+                                                               validity,
+                                                               widgetHandle,
+                                                               subjectId,
+                                                               resourceId,
+                                                               names,
+                                                               values,
+                                                               "some_session");
+    RUNNER_ASSERT(status);
+    status = AceClientStub::getInstance().callPopupAnswer(false,
+                                                          validity,
+                                                          widgetHandle,
+                                                          subjectId,
+                                                          resourceId,
+                                                          names,
+                                                          values,
+                                                          "some_session");
+    RUNNER_ASSERT(!status);
+    status = AceClientStub::getInstance().callPopupAnswer(true,
+                                                          validity,
+                                                          widgetHandle,
+                                                          subjectId,
+                                                          resourceId,
+                                                          names,
+                                                          values,
+                                                          "some_session");
+    RUNNER_ASSERT(status);
+}
+
diff --git a/tests/security_daemon_tests/fake_service.cpp b/tests/security_daemon_tests/fake_service.cpp
new file mode 100644 (file)
index 0000000..4a804a8
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#include "fake_service.h"
+
+bool FakeService::s_initialized = false;
+bool FakeService::s_started = false;
+bool FakeService::s_stopped = false;
+bool FakeService::s_deinitialized = false;
diff --git a/tests/security_daemon_tests/fake_service.h b/tests/security_daemon_tests/fake_service.h
new file mode 100644 (file)
index 0000000..89bea00
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#ifndef _FAKE_SERVICE_H_
+#define _FAKE_SERVICE_H_
+
+#include <security_daemon.h>
+
+class FakeService : public SecurityDaemon::DaemonService {
+public:
+    void initialize() {
+        s_initialized = true;
+    }
+    void start() {
+        s_started = true;
+    }
+    void stop() {
+        s_stopped = true;
+    }
+
+    void deinitialize() {
+        s_deinitialized = true;
+    }
+
+    static bool s_initialized;
+    static bool s_started;
+    static bool s_stopped;
+    static bool s_deinitialized;
+};
+
+DAEMON_REGISTER_SERVICE_MODULE(FakeService)
+
+#endif // _FAKE_SERVICE_H_
diff --git a/tests/security_daemon_tests/ipc-tests-demo.xml b/tests/security_daemon_tests/ipc-tests-demo.xml
new file mode 100644 (file)
index 0000000..4f4e736
--- /dev/null
@@ -0,0 +1,52 @@
+<policy-set id="Policy-1" combine="first-matching-target">
+    <policy>
+        <target>
+            <subject>
+                <subject-match attr="name" match="demoMSG" />
+            </subject>
+        </target>
+        <rule effect="deny" />
+    </policy>
+
+    <policy>
+        <rule effect="permit">
+            <condition>
+                <resource-match attr="device-cap">
+                    resource_id_permit
+                </resource-match>
+            </condition>
+        </rule>
+
+        <rule effect="deny">
+            <condition>
+                <resource-match attr="device-cap">
+                    resource_id_deny
+                </resource-match>
+            </condition>
+        </rule>
+
+        <rule effect="prompt-blanket">
+            <condition>
+                <resource-match attr="device-cap">
+                    resource_id_prompt_blanket
+                </resource-match>
+            </condition>
+        </rule>
+
+        <rule effect="prompt-oneshot">
+            <condition>
+                <resource-match attr="device-cap">
+                    resource_id_prompt_oneshot
+                </resource-match>
+            </condition>
+        </rule>
+
+        <rule effect="prompt-session">
+            <condition>
+                <resource-match attr="device-cap">
+                    resource_id_prompt_session
+                </resource-match>
+            </condition>
+        </rule>
+    </policy>
+</policy-set>
diff --git a/tests/security_daemon_tests/main.cpp b/tests/security_daemon_tests/main.cpp
new file mode 100644 (file)
index 0000000..7c54b99
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+#include <dpl/test/test_runner.h>
+#include <ace-dao-rw/AceDAO.h>
+
+int main(int argc, char** argv)
+{
+    AceDB::AceDAO::attachToThreadRW();
+    int error =
+        DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv);
+    AceDB::AceDAO::detachFromThread();
+    return error;
+}
diff --git a/tests/security_daemon_tests/service_test_cases.cpp b/tests/security_daemon_tests/service_test_cases.cpp
new file mode 100644 (file)
index 0000000..3039df5
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+#include <dpl/test/test_runner.h>
+#include <dpl/framework_efl.h>
+#include <dpl/event/controller.h>
+#include <dpl/generic_event.h>
+#include <dpl/singleton_impl.h>
+
+#include <fake_service.h>
+#include <security_daemon.h>
+
+
+DECLARE_GENERIC_EVENT_0(EndLoopEvent)
+
+class SimpleController : public DPL::Event::Controller<DPL::TypeListDecl<EndLoopEvent>::Type>
+{
+protected:
+    void OnEventReceived(const EndLoopEvent & /* event */){
+        ecore_main_loop_quit();
+    }
+};
+
+typedef DPL::Singleton<SimpleController> SimpleControllerSingleton;
+
+IMPLEMENT_SINGLETON(SimpleController);
+
+RUNNER_TEST_GROUP_INIT(security_daemon)
+
+
+/*
+ * author:      ---
+ * test:        Singleton test
+ * description: Testing state of the daemon
+ * expect:      Daemon should return correct state through FakeService.
+ *
+ */
+RUNNER_TEST(security_daemon_singleton_test) {
+    auto& daemon = SecurityDaemonSingleton::Instance();
+
+    FakeService::s_initialized = false;
+    FakeService::s_started = false;
+    FakeService::s_stopped = false;
+    FakeService::s_deinitialized = false;
+
+    int argc = 0;
+    char ** temp = NULL;
+
+    daemon.initialize(argc, temp);
+
+    RUNNER_ASSERT(FakeService::s_initialized);
+    RUNNER_ASSERT(!FakeService::s_started);
+    RUNNER_ASSERT(!FakeService::s_stopped);
+    RUNNER_ASSERT(!FakeService::s_deinitialized);
+
+    SimpleControllerSingleton::Instance().Touch();
+    CONTROLLER_POST_EVENT(SimpleController, EndLoopEvent());
+
+    daemon.execute();
+    RUNNER_ASSERT(FakeService::s_initialized);
+    RUNNER_ASSERT(FakeService::s_started);
+    RUNNER_ASSERT(!FakeService::s_stopped);
+    RUNNER_ASSERT(!FakeService::s_deinitialized);
+
+
+    daemon.terminate();
+    RUNNER_ASSERT(FakeService::s_initialized);
+    RUNNER_ASSERT(FakeService::s_started);
+    RUNNER_ASSERT(FakeService::s_stopped);
+    RUNNER_ASSERT(!FakeService::s_deinitialized);
+
+    daemon.shutdown();
+    RUNNER_ASSERT(FakeService::s_initialized);
+    RUNNER_ASSERT(FakeService::s_started);
+    RUNNER_ASSERT(FakeService::s_stopped);
+    RUNNER_ASSERT(FakeService::s_deinitialized);
+}
+
+
diff --git a/tests/smack_security/CMakeLists.txt b/tests/smack_security/CMakeLists.txt
new file mode 100644 (file)
index 0000000..eeda3bf
--- /dev/null
@@ -0,0 +1,65 @@
+ADD_CUSTOM_COMMAND(OUTPUT
+    smacksecurity0.wgt
+    smacksecurity1.wgt
+    smacksecurity2.wgt
+    smacksecurity3.wgt
+    smacksecurity4.wgt
+    smacksecurity5.wgt
+    smacksecurity6.wgt
+    COMMAND ${PROJECT_SOURCE_DIR}/tests/smack_security/createSmackSecurityTest.sh
+#    COMMAND mv ${PROJECT_SOURCE_DIR}/tests/smack_security/*wgt ${CMAKE_CURRENT_BINARY_DIR}
+    WORKING_DIRECTORY ${PROJECT_SOURCE_DIR}/tests/smack_security/ 
+    DEPENDS createSmackSecurityTest.sh
+)
+
+ADD_CUSTOM_TARGET(WTF2 ALL
+    DEPENDS
+        smacksecurity0.wgt
+        smacksecurity1.wgt
+        smacksecurity2.wgt
+        smacksecurity3.wgt
+        smacksecurity4.wgt
+        smacksecurity5.wgt
+        smacksecurity6.wgt
+    )
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/tests/smack_security/PermitAllPolicy.xml
+    DESTINATION /usr/etc/ace
+    PERMISSIONS OWNER_READ
+                OWNER_WRITE
+                GROUP_READ
+                WORLD_READ
+    )
+
+
+INSTALL(FILES
+    ${CMAKE_CURRENT_BINARY_DIR}/smacksecurity0.wgt
+    ${CMAKE_CURRENT_BINARY_DIR}/smacksecurity1.wgt
+    ${CMAKE_CURRENT_BINARY_DIR}/smacksecurity2.wgt
+    ${CMAKE_CURRENT_BINARY_DIR}/smacksecurity3.wgt
+    ${CMAKE_CURRENT_BINARY_DIR}/smacksecurity4.wgt
+    ${CMAKE_CURRENT_BINARY_DIR}/smacksecurity5.wgt
+    ${CMAKE_CURRENT_BINARY_DIR}/smacksecurity6.wgt
+    ${CMAKE_CURRENT_BINARY_DIR}/smacksecurity7.wgt
+    ${CMAKE_CURRENT_BINARY_DIR}/smacksecurity8.wgt
+    ${CMAKE_CURRENT_BINARY_DIR}/smacksecurity9.wgt
+    ${CMAKE_CURRENT_BINARY_DIR}/smacksecurity10.wgt
+    DESTINATION /opt/apps/widget/tests/smack/
+    PERMISSIONS OWNER_READ
+                OWNER_WRITE
+                GROUP_READ
+                WORLD_READ
+    )
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/tests/smack_security/wrt-tests-security-smack.sh
+    DESTINATION bin
+    PERMISSIONS OWNER_READ
+                OWNER_WRITE
+                OWNER_EXECUTE
+                GROUP_READ
+                GROUP_EXECUTE
+                WORLD_READ
+                WORLD_EXECUTE
+    )
diff --git a/tests/smack_security/PermitAllPolicy.xml b/tests/smack_security/PermitAllPolicy.xml
new file mode 100644 (file)
index 0000000..558f2dc
--- /dev/null
@@ -0,0 +1,5 @@
+<policy-set id="Policy-1" combine="first-matching-target">
+    <policy>
+        <rule effect="permit" />
+    </policy>
+</policy-set>
diff --git a/tests/smack_security/createSmackSecurityTest.sh b/tests/smack_security/createSmackSecurityTest.sh
new file mode 100755 (executable)
index 0000000..3c78eb4
--- /dev/null
@@ -0,0 +1,43 @@
+#!/bin/sh
+
+#  wrt-plugins
+#
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+
+test_dir=./
+
+III=`pwd`
+echo "KATALOG: $III"
+
+cd $test_dir
+rm -f smacksecurity*.wgt
+
+# remove vim template files
+rm -f `find . -name ".*.swp"`
+rm -f `find . -name "*~"`
+
+ORGPATH=`pwd`
+
+cd smackSecurityTest1
+zip ../smacksecurity0.wgt -r *
+for i in 1 2 3 4 5 6 7 8 9 10
+do
+    cd $ORGPATH/smackSecurityTest2
+    cp config$i.xml config.xml
+    cp js/include$i.js js/include.js
+    zip ../smacksecurity$i.wgt -r *
+done
+
diff --git a/tests/smack_security/smackSecurityTest1/config.xml b/tests/smack_security/smackSecurityTest1/config.xml
new file mode 100644 (file)
index 0000000..f45a80c
--- /dev/null
@@ -0,0 +1,45 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/smackSecurityTest1"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://wacapps.net/api/accelerometer" required="true"/>
+    <feature name="http://wacapps.net/api/filesystem" required="true"/>
+    <feature name="http://wacapps.net/api/pim.calendar" required="true"/>
+    <feature name="http://wacapps.net/api/pim.contact" required="true"/>
+    <feature name="http://wacapps.net/api/pim.task" required="true"/>
+    <feature name="http://wacapps.net/api/orientation" required="true"/>
+
+    <feature name="http://wacapps.net/api/camera" required="true"/>
+    <feature name="http://wacapps.net/api/camera.show" required="true"/>
+
+    <feature name="http://wacapps.net/api/messaging" required="true"/>
+    <feature name="http://wacapps.net/api/messaging.send" required="true"/>
+    <feature name="http://wacapps.net/api/messaging.find" required="true"/>
+    <feature name="http://wacapps.net/api/messaging.write" required="true"/>
+    <feature name="http://wacapps.net/api/messaging.subscribe" required="true"/>
+
+    <feature name="http://wacapps.net/api/deviceinteraction" required="true"/>
+
+    <feature name="http://wacapps.net/api/devicestatus" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/smack_security/smackSecurityTest1/css/style.css b/tests/smack_security/smackSecurityTest1/css/style.css
new file mode 100644 (file)
index 0000000..a4629be
--- /dev/null
@@ -0,0 +1,35 @@
+/* Add style information here */
+* {
+    padding: 0px;
+    margin: 0px;
+    color: #000;
+}
+
+#summary {
+    background-color: #ddd;
+    color: #000;
+    padding: 2px;
+}
+
+#log {
+    color: #fff;
+    width: 400px;
+    display: block;
+}
+
+#log .entry {
+    color: #fff;
+    padding: 2px;
+}
+
+#log .passed {
+    background-color: #45DE1B;
+}
+
+#log .failed {
+    background-color: #DE1B1B;
+}
+
+#log .exception {
+    background-color: #DE1BD8;
+}
diff --git a/tests/smack_security/smackSecurityTest1/index.html b/tests/smack_security/smackSecurityTest1/index.html
new file mode 100644 (file)
index 0000000..2aa3d2f
--- /dev/null
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+    <head>
+        <title>Test engine</title>
+        <meta http-equiv="content-type"
+              content="text/html;charset=utf-8" />
+        <meta http-equiv="Content-Style-Type" content="text/css" />
+        <link rel="stylesheet" type="text/css" href="css/style.css" />
+        <script type="text/javascript" src="js/jquery.js"></script>
+        <!-- jquery.js has to be included first -->
+        <script type="text/javascript" src="js/include.js"></script>
+    </head>
+    <body bgColor="yellow" style="color:black;" onload="TestEngine.doTests();">
+        <div id="summary"></div>
+        <p id="log"></p>
+        <div id="video" style="background: red; width: 100%" />
+        TEST WIDGET
+   </body>
+</html>
+
diff --git a/tests/smack_security/smackSecurityTest1/js/TestEngine.js b/tests/smack_security/smackSecurityTest1/js/TestEngine.js
new file mode 100644 (file)
index 0000000..31c17bb
--- /dev/null
@@ -0,0 +1,1189 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test engine class.
+ *
+ * @author      Wojciech Bielawski(w.bielawski@samsung.com)
+ * @author      Pawel Misiak (p.misiak@samsung.com)
+ * @version     0.1
+ */
+
+var TestEngine = {
+    logText: "",
+    testCaseTimeout: 5 * 1000, //in miliseconds
+    currentCaseTimeout: 5 * 1000,
+    timer: null,
+    countOK: 0,
+    countErr: 0,
+    countException: 0,
+    countIgnored: 0,
+    currentFailings: [],
+    currentTestSuiteName: null,
+    callbackMutex: 0,
+    callbackMethodName: "",
+    currentTestCase: 0,
+    countAllPassed: 0,
+    countAllFailed: 0,
+    testCasesFailedCount: 0,
+    testCasesPassedCount: 0,
+    testCasesFailed: [],
+    testList: [],
+    finalLog: "\n",
+    testSuccessCallback: null,
+    testErrorCallback: null,
+    testSuiteName: null,
+    testSuiteStats: [],
+    resultLogger: new HTMLTestResultLogger('log'),
+    summaryRenderer: new HTMLTestSummaryRenderer('summary'),
+    finalCallback: null,
+
+    stepsArray: null,
+    stepTimeout: null,
+    currentStep: null,
+    errorType: null,
+    errorField: null,
+
+    /*
+     * Values used only as types representations.
+     */
+    STRING: '',
+    NUMBER: 0,
+    OBJECT: {},
+    ARRAY: [],
+    DATE: new Date(),
+    BOOL: false,
+    FUNCTION: function() {},
+
+    /*
+     * Error test possible results.
+     */
+    ERROR_TEST_RESULT: {
+      NOT_RUN: -4,
+      NOT_THROWN: -3,
+      BAD_TYPE: -2,
+      BAD_VALUE: -1,
+      OK: 0
+    },
+
+    /**
+     * Prints specified object in a TreeView like structure.
+     * @param obj Object to print.
+     * @param indent Must be undefined (don't pass anything).
+     */
+    dumpObject: function(obj, indent) {
+        if (indent === undefined) indent = '';
+        else indent += '   ';
+        var prefix = (indent.length == 0 ? indent : indent + '|--');
+        for (var i in obj) {
+            if (typeof(obj[i]) == "object") {
+                TestEngine.log(prefix + i + ":");
+                TestEngine.dumpObject(obj[i], indent);
+            }
+            else
+                TestEngine.log(prefix + i + ": " + obj[i]);
+        }
+    },
+
+    addTest: function(enabled, testFunc, testName, testPrereq)
+    {
+        if (null==testName) {
+            testName="unnamed test"
+        }
+        jsPrint("Add test: " + testName)
+        var data = new Object();
+        data.enabled = enabled;
+        data.testFunc = testFunc;
+        data.testName = testName;
+        data.testPrereq = testPrereq;
+        data.testSuite = TestEngine.testSuiteName;
+        // this.testList.push(testFunc)
+        this.testList.push(data);
+    },
+
+    setTestSuiteName: function(name, timeout)
+    {
+        this.testSuiteName = name;
+        this.testSuiteStats[name] = new Object();
+        this.testSuiteStats[name].passed = 0;
+        this.testSuiteStats[name].failed = 0;
+        this.testSuiteStats[name].assertsOK = 0;
+        this.testSuiteStats[name].assertsErr = 0;
+        TestEngine.currentCaseTimeout =
+            (timeout === undefined) ? TestEngine.testCaseTimeout : timeout;
+    },
+
+    setFinalCallback: function(finalCallbackParam)
+    {
+        this.finalCallback = finalCallbackParam;
+    },
+
+    log: function(text)
+    {
+        try
+        {
+            jsPrint(text);
+            this.logText += text + "<br/>";
+            this.finalLog += text + "\n";
+            // document.getElementById(TestEngine.currentTestSuite).innerHTML += text + "<br/>";
+            //document.getElementById('log').innerHTML += text + "<br/>";
+        }
+        catch(err)
+        {
+            this.countException++;
+            jsPrint("   TestEngine.log failure: " + err.message);
+        }
+    },
+
+    logException: function(text)
+    {
+        try
+        {
+            TestEngine.countException++;
+            TestEngine.log("[EXCEPTION] " + text);
+            TestEngine.currentFailings.push(text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logErr failure: " + err.message);
+        }
+    },
+
+    logErr: function(text)
+    {
+        try
+        {
+            TestEngine.countErr++;
+            TestEngine.log("[FAILED] " + text);
+            TestEngine.currentFailings.push(text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logErr failure: " + err.message);
+        }
+    },
+
+    logIgnored: function(text)
+    {
+        try
+        {
+            TestEngine.countIgnored++;
+            TestEngine.log("[IGNORED] " + text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logErr failure: " + err.message);
+        }
+    },
+
+    logOK: function(text)
+    {
+        try
+        {
+            TestEngine.countOK++;
+            TestEngine.log("[OK] " + text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logOK failure: " + err.message);
+        }
+    },
+
+    test: function(text, value)
+    {
+        try
+        {
+            if(typeof(value) == "undefined")
+            {
+                TestEngine.logErr("value not defined for test: '" + text + "'");
+            }
+            else if(!value)
+            {
+                TestEngine.logErr(text);
+            }
+            else
+            {
+                TestEngine.logOK(text);
+                return true;
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.test failure: " + err.message);
+        }
+        return false;
+    },
+
+    /**
+     * Sets error type used in every typePresetError check.
+     * @param type Type of an error/exception.
+     */
+    setErrorType: function(type)
+    {
+        TestEngine.errorType = type;
+    },
+
+    /**
+     * Sets error field used in every typePresetError check.
+     * @param field Name of the field in error structure to check its value.
+     */
+    setErrorField: function(field)
+    {
+        TestEngine.errorField = field;
+    },
+
+    /**
+     * Checks if specified expression throws a specified error.
+     * Expression must be enclosed in a function. Use setErrorType and
+     * setErrorField to set what error to look for.
+     * Error type must be set but if error field is left unset (i.e. null)
+     * then whole exception object is compared to specified value.
+     * @param msg Text to display for this test.
+     * @param fn Function eclosing the expression one wants to verify.
+     * @param value Value of an error/exception one looks for.
+     */
+    testPresetError: function(msg, fn, value)
+    {
+        if (TestEngine.errorType === null) {
+            TestEngine.logException("testPresetError skipped. Set error type first.");
+            return;
+        }
+
+        return TestEngine.testError(msg, fn, TestEngine.errorType,
+            TestEngine.errorField, value);
+    },
+
+    /**
+     * Checks if specified expression throws a specified error.
+     * This is a more general version of testPresetError function.
+     * Expression must be enclosed in a function.
+     * Error type must be set but if error field is left unset (i.e. null)
+     * then whole exception object is compared to specified value.
+     * @param msg Text to display for this test.
+     * @param fn Function eclosing the expression one wants to verify.
+     * @param errType Type of desired error/exception.
+     * @param errField Property from exception structure to look for exception
+     * value.
+     * @param errValue Value of an error/exception one looks for.
+     */
+    testError: function(msg, fn, errType, errField, errValue)
+    {
+        if (errType === null) {
+            TestEngine.logException("testError skipped. Error type can't be null.");
+            return TestEngine.ERROR_TEST_RESULT.NOT_RUN;
+        }
+
+        try {
+            fn();
+            TestEngine.logErr(msg + ' Exception has not been thrown.');
+            return TestEngine.ERROR_TEST_RESULT.NOT_THROWN;
+        }
+        catch (ex) {
+            if (ex instanceof errType) {
+                var exValue = (errField !== null ? ex[errField] : ex);
+                if (exValue === errValue) {
+                    TestEngine.logOK(msg + ' [' + errValue + ']');
+                    return TestEngine.ERROR_TEST_RESULT.OK;
+                }
+                else {
+                    TestEngine.logErr(msg + ' Exception is not of value ' + errValue);
+                    return TestEngine.ERROR_TEST_RESULT.BAD_VALUE;
+                }
+            }
+            else {
+                TestEngine.logErr(msg + ' Exception is of wrong type.');
+                return TestEngine.ERROR_TEST_RESULT.BAD_TYPE;
+            }
+        }
+    },
+
+    testPresence: function(text, object)
+    {
+        try
+        {
+            if(object === undefined)
+            {
+                TestEngine.logErr("value not defined. Name: " + text);
+            }
+            else
+            {
+                TestEngine.logOK("object " + text + " present");
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testPresence failure: " + err.message);
+        }
+    },
+
+    /**
+     * Checks whether object implements given property.
+     * In addition it also checks whether any exception (e.g. "Not Supported")
+     * is thrown.
+     * @param object Object to check property for.
+     * @param property Property to look for.
+     * @return True if object implements such property, false otherwise.
+     */
+    testPresence2: function(object, property)
+    {
+        var result = property in object;
+        if (result)
+        {
+            TestEngine.logOK("property " + property + " present");
+        }
+        else
+        {
+            TestEngine.logErr("property " + property + " absent");
+        }
+        return result;
+    },
+
+
+    /**
+     * Checks whether mainObj object equals templateObj object, property by
+     * property.
+     * Runs recursively through all the properties of templateObj object and
+     * checks if they exist and are equal to those in mainObj object.
+     * mainObj has to implement no less properties than templateObj.
+     * @param mainObj Object to check for properties implementation.
+     * @param templateObj Object to verify properties against.
+     * @return True if mainObj has at least the same properties as templateObj,
+     *         false otherwise.
+     */
+    checkObjectsEqual: function(mainObj, templateObj)
+    {
+        try
+        {
+            if ((!mainObj && templateObj) || (typeof(mainObj) != typeof(templateObj))) {
+                return false;
+            }
+            else if (isNumber(templateObj) || isString(templateObj) || isBoolean(templateObj)) {
+                return (mainObj === templateObj);
+            }
+            else if (isDate(templateObj)) {
+                return (mainObj.valueOf() === templateObj.valueOf());
+            }
+            else {
+                for (var i in templateObj) {
+                    if (!TestEngine.checkObjectsEqual(mainObj[i], templateObj[i])) {
+                        return false;
+                    }
+                }
+            }
+        }
+        catch(err)
+        {
+            TestEngine.logException("TestEngine.checkObjectsEqual failure: " + err.message);
+            return false;
+        }
+        return true;
+    },
+
+    // test properties of given object. Steps:
+    // - check name presence
+    // - check default value (if not null value passed)
+    // - check if name is writable
+    //
+    // description of properties array:
+    // [0] - property name
+    // [1] - default value - check if property equals given value
+    //          undefined or null - disable check
+    // [2] - value to do writability test - try to write given value
+    //          undefined or null - don't check writability
+    // [3] - indicates if property should be read-only
+    // [4] - assumed type, undefined value skips this check
+    testProperties: function(object, props)
+    {
+        var result = new Object();
+        try
+        {
+            for(var i in props)
+            {
+                var name = props[i][0];
+                var defaultVal = props[i][1];
+                var setVal = props[i][2];
+                var isReadonly = props[i][3];
+                var type = props[i][4];
+                var errors = TestEngine.countErr + TestEngine.countException;
+
+                if ((typeof(name) != "string") || (name == ""))
+                {
+                    TestEngine.logException("Property name not defined, skipping it.");
+                    continue;
+                }
+
+                result[name] = false;
+                if (TestEngine.testPresence2(object, name)) {
+                    if ((defaultVal != null) && (defaultVal !== undefined))
+                    {
+                        var isObjectEqual = TestEngine.checkObjectsEqual(object[name], defaultVal);
+                        TestEngine.test(name + " default value", isObjectEqual);
+                    }
+
+                    if ((setVal != null) && (setVal !== undefined))
+                    {
+                        // try-catch is needed when SetProperty returns 'false'
+                        if(setVal === defaultVal)
+                        {
+                            TestEngine.logException("Default value and set value are equal");
+                            continue;
+                        }
+                        try { object[name] = setVal; }
+                        catch (e) { }
+                        if (typeof(isReadonly) == "undefined")
+                        {
+                            TestEngine.test(name + " writability, reason: isReadonly not specified", false);
+                        }
+                        if (isReadonly)
+                        {
+                            TestEngine.test(name + " writability", object[name] != setVal);
+                        }
+                        else
+                        {
+                            var isObjectEqual = TestEngine.checkObjectsEqual(object[name], setVal);
+                            TestEngine.test(name + " writability", isObjectEqual);
+                        }
+                    }
+
+                    if (type !== undefined) {
+                        var isType = (typeof(object[name]) == typeof(type));
+                        if (typeof(type) == 'object') {
+                            if (isArray(type)) {
+                                isType = isArray(object[name]);
+                            }
+                            else if (isDate(type)) {
+                                isType = isDate(object[name]);
+                            }
+                        }
+                        TestEngine.test(name + " type check.", isType);
+                    }
+                }
+                if (errors == TestEngine.countErr + TestEngine.countException) {
+                    result[name] = true;
+                }
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testProperties failure: " + err.message);
+        }
+        return result;
+    },
+
+    startTestCase: function()
+    {
+        try
+        {
+            TestEngine.countOK = 0;
+            TestEngine.countErr = 0;
+            TestEngine.countException = 0;
+            TestEngine.countIgnored = 0;
+            TestEngine.currentFailings = [];
+            TestEngine.timer = setTimeout(TestEngine.timeout, TestEngine.currentCaseTimeout);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.startTestCase failure: " + err.message);
+        }
+
+    },
+
+    endTestCase: function(testCase)
+    {
+        try
+        {
+            if(this.timer === null)
+            {
+                return;
+            }
+
+            clearTimeout(this.timer);
+            this.log("");
+            var ignored = this.countIgnored > 0;
+            var failed = this.countErr || ((this.countOK+this.countErr)<1) || this.countException || ignored;
+
+            if (widget.__test) {
+                if (ignored) {
+                    widget.__test.collectIgnored(testCase.testName);
+                } else if (failed) {
+                    widget.__test.collectFail(testCase.testName, TestEngine.currentFailings.join('; '));
+                } else {
+                    widget.__test.collectPass(testCase.testName);
+                }
+            }
+            this.log("Test case " + (failed ? "FAILED" : "PASSED"));
+            this.log("Passed: " + this.countOK);
+            this.log("Failed: " + this.countErr);
+            if(this.countException)
+            {
+                this.log("Exception occured!");
+            }
+
+            this.countAllPassed += this.countOK;
+            this.countAllFailed += this.countErr;
+            this.testSuiteStats[testCase.testSuite].assertsOK += this.countOK;
+            this.testSuiteStats[testCase.testSuite].assertsErr += this.countErr;
+
+            if(failed)
+            {
+                TestEngine.testCasesFailedCount++;
+                this.testSuiteStats[testCase.testSuite].failed++;
+                if (isVerbose()) {
+                    TestEngine.testCasesFailed.push(testCase.testName);
+                }
+                TestEngine.resultLogger.logFail(testCase.testName);
+            }
+            else
+            {
+                TestEngine.testCasesPassedCount++;
+                this.testSuiteStats[testCase.testSuite].passed++;
+                TestEngine.resultLogger.logPass(testCase.testName);
+            }
+            TestEngine.summaryRenderer.render(TestEngine);
+        }
+        catch(err)
+        {
+            this.countException++;
+            jsPrint("   TestEngine.endTestCase failure:" + err.message);
+        }
+    },
+
+    timeout: function()
+    {
+        try
+        {
+            TestEngine.callbackMutex = 0;
+            TestEngine.logErr("Widget run timeout.", false);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.timeout failure:" + err.message);
+        }
+    },
+
+    /**
+     * Registers callbacks for asynchronous function.
+     *
+     * To avoid finish test case before callbacks will execute it's necessary
+     * to register callbacks in the engine.
+     *
+     * @param methodName Testcase name, suggested asynchronous function name.
+     * @param testSuccessCallback Callback that will be executed on success.
+     * @param testErrorCallback Callback that will be executed on failure.
+     * @param callbacksCount number of callbacks to register.
+     * @return An object with defined functions "successCallback" and "errorCallback" you
+     *          need to pass as arguments to asynchronous function  e.g.
+     *
+     * function success() {  }
+     * function failure() {  }
+     *
+     * {
+         *      var obj = TestEngine.registerCallback("myAsyncFunc", success, failure);
+         *      myAsyncFunc(obj.successCallback, obj.errorCallback);
+         * }
+     */
+    registerCallback: function(methodName, testSuccessCallback, testErrorCallback, callbacksCount)
+    {
+        try
+        {
+            if(callbacksCount !== undefined && callbacksCount > 0){
+                TestEngine.callbackMutex += callbacksCount;
+            }
+            else {
+                TestEngine.callbackMutex++;
+            }
+            TestEngine.callbackMethodName = methodName;
+            TestEngine.testSuccessCallback = testSuccessCallback;
+            TestEngine.testErrorCallback = testErrorCallback;
+
+            var retObj = new Object();
+            retObj.callbackMethodName = methodName;
+            retObj.testSuccessCallback = testSuccessCallback;
+            retObj.successCallback = function(param){
+                try
+                {
+                    if((typeof retObj.testSuccessCallback != "undefined") && (retObj.testSuccessCallback !== null))
+                    {
+                        retObj.testSuccessCallback(param);
+                    }
+                    else
+                    {
+                        TestEngine.logOK(retObj.callbackMethodName + " succeed");
+                    }
+                }
+                catch(err)
+                {
+                    TestEngine.countException++;
+                    jsPrint("   TestEngine.this.successCallback failure:" + err.message);
+                }
+                TestEngine.callbackMutex--;
+            };
+
+            retObj.testErrorCallback = testErrorCallback;
+            retObj.errorCallback = function(param){
+                try
+                {
+                    if((typeof retObj.testErrorCallback != "undefined") && (retObj.testErrorCallback !== null))
+                    {
+                        retObj.testErrorCallback(param);
+                    }
+                    else
+                    {
+                        TestEngine.logErr(retObj.callbackMethodName + " failed");
+                    }
+                }
+                catch(err)
+                {
+                    TestEngine.countException++;
+                    jsPrint("   TestEngine.retObj.errorCallback failure:" + err.message);
+                }
+                TestEngine.callbackMutex--;
+            };
+
+            return retObj;
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.registerCallback failure:" + err.message);
+        }
+    },
+
+    successCallback: function(params)
+    {
+        TestEngine.log("[Warning] Function TestEngine.successCallback deprecated");
+        try
+        {
+            TestEngine.callbackMutex--;
+            if(typeof TestEngine.testSuccessCallback != "undefined")
+            {
+                TestEngine.testSuccessCallback(params);
+            }
+            else
+            {
+                TestEngine.logOK(TestEngine.callbackMethodName + " succeed");
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.successCallback failure:" + err.message);
+        }
+    },
+
+    errorCallback: function(params)
+    {
+        TestEngine.log("[Warning] Function TestEngine.errorCallback deprecated");
+        try
+        {
+            TestEngine.callbackMutex--;
+            if(typeof TestEngine.testErrorCallback != "undefined")
+            {
+                TestEngine.testErrorCallback(params);
+            }
+            else
+            {
+                TestEngine.logErr(TestEngine.callbackMethodName + " failed");
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.errorCallback failure:" + err.message);
+        }
+    },
+
+    waitForCallback: function()
+    {
+        try
+        {
+            //    while( TestEngine.callbackMutex )
+            {
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.waitForCallback failure:" + err.message);
+        }
+    },
+
+    /*
+     * code - error code which is expected
+     * object - object which will be used to call method
+     * functionName - method name to call
+     * restArguments - rest arguments which will be passed to callback
+     *
+     * example:
+     * TestEngine.catchError(10001, bondi.messaging, findSMSs, succCallback, null, filter)
+     */
+    catchError: function(code, object, functionName, restArguments /* , ... */ )
+    {
+        try
+        {
+            TestEngine.log("TestEngine.catchError is DEPRECATED. Please use TestEngine.catchErrorType.");
+            var error;
+            try
+            {
+                var newArgs = []
+                for (var i=3;i<arguments.length;i++) {
+                    newArgs.push(arguments[i])
+                }
+                var retVal = null;
+                retVal = object[functionName].apply(object, newArgs);
+                TestEngine.logErr(functionName + " no error thrown");
+                return retVal;
+            }
+            catch(error)
+            {
+                TestEngine.testPresence("<error code from: " + functionName + ">", error.code);
+                TestEngine.test("Error number", error.code == code);
+                return;
+            }
+            TestEngine.logErr("Function " + functionName + " desn't throw");
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testError failure:" + err.message);
+        }
+    },
+
+    /*
+     * errorTypeName - attribute name of catched exception to compare with code
+     * code - error code which is expected
+     * object - object which will be used to call method
+     * functionName - method name to call
+     * restArguments - rest arguments which will be passed to callback
+     *
+     * example:
+     * TestEngine.catchErrorType("code", 10001, bondi.messaging, findSMSs, succCallback, null, filter)
+     */
+    catchErrorType: function(errorTypeName, code, object, functionName, restArguments /* , ... */ )
+    {
+        try
+        {
+            var error;
+            try
+            {
+                var newArgs = []
+                for (var i=4;i<arguments.length;i++) {
+                    newArgs.push(arguments[i])
+                }
+                var retVal = null;
+                if (arguments.length < 4) {
+                    TestEngine.logErr("Wrong catchErrorType usage.");
+                    return retVal;
+                }
+                retVal = object[functionName].apply(object, newArgs);
+                TestEngine.logErr(functionName + " no error thrown");
+                return retVal;
+            }
+            catch(error)
+            {
+                TestEngine.testPresence("<error code from: " + functionName + ">", error[errorTypeName]);
+                TestEngine.test("Error number", error[errorTypeName] == code);
+                return;
+            }
+            TestEngine.logErr("Function " + functionName + " desn't throw");
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testError failure:" + err.message);
+        }
+    },
+
+    // Executes step by step functions passed in steps array
+    // and waits after every execution time defined in timeInterval
+    executeSteps: function(steps, timeInterval)
+    {
+        try
+        {
+            if(typeof(timeInterval) == "undefined")
+            {
+                timeInterval = 100; //default value
+            }
+
+            TestEngine.stepsArray = steps;
+            TestEngine.stepTimeout = timeInterval;
+            TestEngine.currentStep = 0;
+            TestEngine.executeNextStep();
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.executeSteps failure:" + err.message);
+        }
+    },
+
+    executeNextStep: function()
+    {
+        try
+        {
+            if( TestEngine.stepsArray && (TestEngine.currentStep < TestEngine.stepsArray.length) )
+            {
+                if( isArray( TestEngine.stepsArray[ TestEngine.currentStep ] ) )
+                {
+                    TestEngine.stepsArray[ TestEngine.currentStep ][0]();
+                    setTimeout( TestEngine.executeNextStep, TestEngine.stepsArray[ TestEngine.currentStep ][1] );
+
+                }
+                else
+                {
+                    TestEngine.stepsArray[ TestEngine.currentStep ]();
+                    setTimeout( TestEngine.executeNextStep, TestEngine.stepTimeout );
+                }
+                TestEngine.currentStep++;
+            }
+            else
+            {
+                TestEngine.currentStep = null;
+                TestEngine.stepTimeout = null;
+                TestEngine.stepsArray = null;
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.executeNextStep failure:" + err.message);
+            jsPrint("   Current step:" + TestEngine.currentStep);
+
+            TestEngine.currentStep = null;
+            TestEngine.stepTimeout = null;
+            TestEngine.stepsArray = null;
+        }
+    },
+
+    enumerate: function(obj, level)
+    {
+        try
+        {
+            if(typeof level == "undefined")
+            {
+                TestEngine.log(obj + ":");
+                level = "";
+            }
+            for(i in obj)
+            {
+                if(!(typeof obj[i] == "object" || typeof obj[i] == "array"))
+                {
+                    TestEngine.log(level + i + " =  " + obj[i]);
+                }
+                else
+                {
+                    TestEngine.log(level + i + " =  ");
+                    TestEngine.enumerate(obj[i], level + "----");
+                }
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.enumerate failure:" + err.message);
+        }
+    },
+
+    doTests: function()
+    {
+        try
+        {
+            TestEngine.testCasesFailed = [];
+            TestEngine.test("jsPrint presence", jsPrint);
+            TestEngine.test("Widget presence", window.widget);
+            TestEngine.doNextTestCase();
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.doTests failure:" + err.message);
+        }
+    },
+
+    showSuitesStats: function()
+    {
+        try
+        {
+            jsPrint("============ Test suites:");
+            for(var i in this.testSuiteStats)
+            {
+                jsPrint(i + " - " + this.testSuiteStats[i].passed + " passed, " + this.testSuiteStats[i].failed + " failed," + "   asserts: " + this.testSuiteStats[i].assertsOK + " passed, " + this.testSuiteStats[i].assertsErr + " failed"); }
+        }
+        catch(err)
+        {
+            jsPrint("   TestEngine.showSuitesStats failure:" + err.message);
+        }
+    },
+
+    doNextTestCase: function()
+    {
+        try
+        {
+            if( TestEngine.stepsArray !== null || (TestEngine.callbackMutex > 0))
+            {
+                setTimeout( TestEngine.doNextTestCase, 100 );
+                return;
+            }
+
+            if(TestEngine.currentTestCase)
+            {
+                TestEngine.endTestCase(TestEngine.testList[TestEngine.currentTestCase-1]);
+            }
+
+            if( TestEngine.testList.length == TestEngine.currentTestCase )
+            {
+                if (widget.__test) {
+                    widget.__test.outputResults();
+                }
+                jsPrint("============");
+                jsPrint(TestEngine.finalLog);
+                TestEngine.showSuitesStats();
+                jsPrint("============ Summary:");
+                jsPrint("Test cases all: " + TestEngine.testList.length);
+                jsPrint("Test cases passed: " + TestEngine.testCasesPassedCount);
+                jsPrint("Test cases failed: " + TestEngine.testCasesFailedCount);
+                jsPrint("Asserts passed: " + TestEngine.countAllPassed);
+                jsPrint("Asserts failed: " + TestEngine.countAllFailed);
+                if (isVerbose()) {
+                    jsPrint("============ Failing test cases:");
+                    for (i = 0; i < TestEngine.testCasesFailed.length; ++i) {
+                        jsPrint(TestEngine.testCasesFailed[i]);
+                    }
+                }
+                TestEngine.summaryRenderer.render(TestEngine);
+
+                if(typeof TestEngine.finalCallback != "undefined")
+                {
+                    jsPrint("Registering final callback");
+                    TestEngine.summaryRenderer.render(TestEngine);
+                    setTimeout(TestEngine.finalCallback, 4000);
+                } else {
+                    jsPrint("Final callback was not registered.");
+                }
+                return;
+            }
+
+            var i = TestEngine.currentTestCase++;
+            try
+            {
+                if (widget.__test) {
+                    if (TestEngine.currentTestSuiteName != TestEngine.testList[i].testSuite) {
+                        TestEngine.currentTestSuiteName = TestEngine.testList[i].testSuite;
+                        widget.__test.collectGroup(TestEngine.testList[i].testSuite);
+                    }
+                }
+                TestEngine.log("");
+                TestEngine.log("==== Test case: " + TestEngine.testList[i].testName);
+                TestEngine.startTestCase();
+                var testPrereq = true;
+                if (TestEngine.testList[i].testPrereq !== undefined)
+                {
+                    testPrereq = TestEngine.testList[i].testPrereq();
+                }
+                if (testPrereq)
+                {
+                    if(TestEngine.testList[i].enabled)
+                    {
+                        TestEngine.testList[i].testFunc();
+                    }
+                    else
+                    {
+                        TestEngine.logIgnored("Test disabled");
+                    }
+
+                }
+                else {
+                    TestEngine.logException
+                    ("Test case prerequisites unfulfilled.  Skipping it.");
+                }
+            }
+            catch(err)
+            {
+                TestEngine.countException++;
+                TestEngine.log("   Test case '" + TestEngine.testList[i].testName + "' failed:" + err.message);
+            }
+            setTimeout( TestEngine.doNextTestCase, 100 );
+        }
+        catch(err)
+        {
+            jsPrint("   TestEngine.doNextTestCase failure:" + err.message);
+        }
+    }
+};
+
+function isUndefined(val)
+{
+    if (typeof val == "undefined") {
+        return true;
+    }
+    return false;
+}
+function isNull(val)
+{
+    return val === null;
+}
+function isString(val) {
+    if (typeof val == typeof "") {
+        return true;
+    }
+    return false;
+}
+function isNumber(val) {
+    if (typeof val == typeof 0) {
+        return true
+    }
+    return false;
+}
+function isDate(val) {
+    return (val instanceof Date);
+}
+function isFunction(val) {
+    return (typeof(val) == 'function');
+}
+function isBoolean(val) {
+    if (typeof val == typeof true) {
+        return true
+    }
+    return false;
+}
+function isArray(val) {
+    return (val instanceof Array);
+}
+function isObject(val) {
+    return (val instanceof Object);
+}
+
+function isVerbose() {
+    return ((typeof(VERBOSE) != "undefined") && (VERBOSE === 1));
+}
+
+/**
+ * Tests results logger.
+ */
+function HTMLTestResultLogger(sinkId) {
+
+  /**
+   * Logs a message.
+   * @param message Message to log.
+   * @param status Status of the message (PASSED, FAILED, EXCEPTION).
+   *               By default status is set to PASSED.
+   */
+  this.log = function(message, status) {
+    if (arguments.length < 2) throw "Not enough number of arguments.";
+    $(sink).append(createLogEntry(message, status));
+  }
+
+  /**
+   * Helper functions.
+   */
+  this.logPass = function(message) {
+    if (arguments.length < 1) throw "Not enough number of arguments.";
+    this.log(message, HTMLTestResultLogger.PASSED);
+  }
+
+  this.logFail = function(message) {
+    if (arguments.length < 1) throw "Not enough number of arguments.";
+    this.log(message, HTMLTestResultLogger.FAILED);
+  }
+
+  $(document).ready(function() {
+    sink = document.getElementById(sinkId);
+    if (null === sink) throw "Summary element unavailable.";
+  });
+
+  var createLogEntry = function(message, status) {
+    var entry = '<div class="entry ' + status + '">';
+    entry +=    message.toString();
+    entry +=    '</div>';
+    return entry;
+  }
+
+  var id = sinkId;
+  var sink = null;
+}
+
+HTMLTestResultLogger.PASSED = "passed";
+HTMLTestResultLogger.FAILED = "failed";
+HTMLTestResultLogger.EXCEPTION = "exception";
+
+
+/**
+ * Tests summary renderer.
+ */
+function HTMLTestSummaryRenderer(summaryId) {
+
+  this.render = function(engine) {
+    if (arguments.length < 1) throw "Not enough arguments.";
+
+    $('#_summary_numberOfRunTests').text(engine.currentTestCase);
+    $('#_summary_numberOfAllTests').text(engine.testList.length);
+    $('#_summary_numberOfPassedTests').text(engine.testCasesPassedCount);
+    $('#_summary_numberOfPassedAsserts').text(engine.countAllPassed);
+    $('#_summary_numberOfFailedTests').text(engine.testCasesFailedCount);
+    $('#_summary_numberOfFailedAsserts').text(engine.countAllFailed);
+    for(var suiteName in engine.testSuiteStats) {
+      if (!isSuiteStarted(engine.testSuiteStats[suiteName])) continue;
+      renderSuite(suiteName, engine.testSuiteStats[suiteName]);
+    }
+  }
+
+  $(document).ready(function() {
+    summary = document.getElementById(summaryId);
+    if (null === summary) {
+      throw "Summary element unavailable.";
+    }
+    setupSummary(summary);
+  });
+
+  var isSuiteStarted = function(stats) {
+    return (stats.passed + stats.failed != 0);
+  }
+
+  var renderSuite = function(name, stats) {
+    var elementId = '_summary_suite_' + name;
+    var element = document.getElementById(elementId);
+    if (null === element) {
+      element = $('<div id="' + elementId + '">' + name + ': '+ '<span name="stats"></span></div>');
+      $(summary).append(element);
+    }
+    var elementStats = $(element).children('span[name="stats"]');
+    elementStats.text(stats.passed + '(' + stats.assertsOK + ')' + ' passed, ' +
+                      stats.failed + '(' + stats.assertsErr + ')' + ' failed');
+  }
+
+  var setupSummary = function(summary) {
+    var run  = '<div>Run: <span id="_summary_numberOfRunTests">0</span>';
+        run += ' of <span id="_summary_numberOfAllTests">0</span></div>';
+    var current = '<div>Current: <span id="_summary_currentTest">0</span></div>';
+    var passed  = '<div>Passed: <span id="_summary_numberOfPassedTests">0</span>';
+        passed += '(<span id="_summary_numberOfPassedAsserts">0</span>)</div>';
+    var failed  = '<div>Failed: <span id="_summary_numberOfFailedTests">0</span>';
+        failed += '(<span id="_summary_numberOfFailedAsserts">0</span>)</div>';
+    $(summary).append(run).append(passed).append(failed);
+  }
+
+  var id = summaryId;
+  var summary = null;
+}
+
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/CloseCallback.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/CloseCallback.js
new file mode 100644 (file)
index 0000000..102e865
--- /dev/null
@@ -0,0 +1 @@
+TestEngine.setFinalCallback(function(){ jsPrint("closing window"); window.close(); });
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestAccelerometer.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestAccelerometer.js
new file mode 100644 (file)
index 0000000..167a944
--- /dev/null
@@ -0,0 +1,152 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test Accelerometer class.
+ *
+ * @author      xiangguo.qi (xiangguo.qi @samsung.com)
+ * @version     0.1
+ */
+
+
+var AccelerometerObj = deviceapis.accelerometer;
+var WatchID = "";
+// Accelerometer001
+function presenceTest()
+{
+    TestEngine.test("Checking checking", true);
+    TestEngine.test("Checking deviceapis object", deviceapis);
+    TestEngine.test("Checking Accelerometer object", AccelerometerObj);
+
+    TestEngine.test("Checking type of getCurrentAcceleration", isFunction(AccelerometerObj.getCurrentAcceleration));
+    TestEngine.test("Checking type of watchAcceleration", isFunction(AccelerometerObj.watchAcceleration));
+    TestEngine.test("Checking type of clearWatch", isFunction(AccelerometerObj.clearWatch));
+}
+
+// Accelerometer002
+function getCurrentAccelerationInvalidParamsTest()
+{
+    // Following two tests should silently fail according to WAC 2.0
+    TestEngine.test("getCurrentAcceleration undefined callback", isUndefined(AccelerometerObj.getCurrentAcceleration(undefined)));
+    TestEngine.test("getCurrentAcceleration null callback", isUndefined(AccelerometerObj.getCurrentAcceleration(null)));
+    // Following tests should throw errors according to WAC 2.0
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "getCurrentAcceleration", "test");
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "getCurrentAcceleration", new Date());
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "getCurrentAcceleration", [6, 6, 6]);
+}
+
+
+// Accelerometer003
+function getCurrentAccelerationTest()
+{
+    getCurrentAccelerationCheck();
+}
+
+function getCurrentAccelerationCheck()
+{
+       function getSuccess(acceleration) {
+        TestEngine.test("get current acceleration",true);
+               TestEngine.test("acceleration.xAxis", isNumber(acceleration.xAxis));
+               TestEngine.test("acceleration.yAxis", isNumber(acceleration.yAxis));
+               TestEngine.test("acceleration.zAxis", isNumber(acceleration.zAxis));
+    }
+
+    function getFail() {
+        TestEngine.test("get current acceleration",false);
+    }
+
+    var cbObj = TestEngine.registerCallback("getCurrentAcceleration", getSuccess, getFail);
+    AccelerometerObj.getCurrentAcceleration(cbObj.successCallback, cbObj.errorCallback);
+
+}
+
+// Accelerometer004
+function watchAccelerationInvalidParamsTest()
+{
+    // Following two tests should silently fail according to WAC 2.0
+    TestEngine.test("watchAcceleration undefined callback", isUndefined(AccelerometerObj.watchAcceleration(undefined)));
+    TestEngine.test("watchAcceleration null callback", isUndefined(AccelerometerObj.watchAcceleration(null)));
+    // Following tests should throw errors according to WAC 2.0
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "watchAcceleration", "test");
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "watchAcceleration", new Date());
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "watchAcceleration", [6, 6, 6]);
+    // Following tests should ignore optional parameter if it is of invalid type, according to WAC 2.0
+    TestEngine.test("watchAcceleration ignore invalid params", isNumber(AccelerometerObj.watchAcceleration(function(){}, function(){}, "test")));
+    TestEngine.test("watchAcceleration ignore invalid params", isNumber(AccelerometerObj.watchAcceleration(function(){}, function(){}, {minNotificationInterval:"test"})));
+    TestEngine.test("watchAcceleration ignore invalid params", isNumber(AccelerometerObj.watchAcceleration(function(){}, function(){}, {minNotificationInterval:true})));
+}
+
+
+// Accelerometer005
+function watchAccelerationTest()
+{
+    watchAccelerationCheck();
+}
+
+function watchAccelerationCheck()
+{
+       function watchSuccess(acceleration) {
+        TestEngine.test("watch acceleration",true);
+               TestEngine.test("acceleration.xAxis", isNumber(acceleration.xAxis));
+               TestEngine.test("acceleration.yAxis", isNumber(acceleration.yAxis));
+               TestEngine.test("acceleration.zAxis", isNumber(acceleration.zAxis));
+
+    }
+
+    function watchFail() {
+        TestEngine.test("watch acceleration",false);
+    }
+
+    var cbObj = TestEngine.registerCallback("watchAcceleration", watchSuccess, watchFail);
+    WatchID = AccelerometerObj.watchAcceleration(cbObj.successCallback, cbObj.errorCallback, {minNotificationInterval:2000});
+
+}
+
+// Accelerometer006
+function clearWatchTest()
+{
+    var ids = [WatchID, null, new Date(), true, undefined, "test", [6, 6, 6]];
+    for (var i =0; i < ids.length; ++i) {
+        try
+        {
+            AccelerometerObj.clearWatch(ids[i]);
+            TestEngine.logOK("clearWatch OK");
+        }
+        catch (error) {
+            TestEngine.logErr("clearWatch Error");
+        }
+    }
+
+    try
+    {
+        AccelerometerObj.clearWatch();
+        TestEngine.logOK("clearWatch OK");
+    }
+    catch (error) {
+        TestEngine.logErr("clearWatch Error");
+    }
+}
+
+
+//=============================================================================
+
+TestEngine.setTestSuiteName("[WAC2.0][Accelerometer]", 60*1000); //2min time out for callbacks
+//TestEngine.addTest(true, presenceTest, "[WAC2.0][Accelerometer] Accelerometer functions presence test");
+//TestEngine.addTest(true, getCurrentAccelerationInvalidParamsTest, "[WAC2.0][Accelerometer] getCurrentAcceleration invalid params  test");
+TestEngine.addTest(true, getCurrentAccelerationTest, "[WAC2.0][Accelerometer] getCurrentAcceleration test");
+//TestEngine.addTest(true, watchAccelerationInvalidParamsTest, "[WAC2.0][Accelerometer] watchAcceleration invalid params  test");
+//TestEngine.addTest(true, watchAccelerationTest, "[WAC2.0][Accelerometer] watchtAcceleration test");
+//TestEngine.addTest(true, clearWatchTest, "[WAC2.0][Accelerometer] clearWatch test");
+
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestCalendar.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestCalendar.js
new file mode 100644 (file)
index 0000000..e2c946d
--- /dev/null
@@ -0,0 +1,1577 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test calendar class.
+ *
+ * @author      Lukasz Marek (l.marek@samsung.com)
+ * @version     0.1
+ */
+
+var TYPE_MISMATCH_ERR = 17;
+var INVALID_VALUES_ERR = 22;
+var NOT_FOUND_ERR = 8;
+
+var TestCalendar = {
+    calendar: null,
+    event:null,
+    old_event:null,
+    num_events:null,
+    found_events:null,
+    all_events:null,
+    expectedErrorCode: null,
+
+    createTestEvent: function (response)
+    {
+        return TestCalendar.calendar.createEvent({description:'Test Event 1',
+                summary:'Event created to test event creation',
+                startTime: new Date(2009, 3, 30, 10, 0),
+                duration : 60,
+                location:'London',
+                recurrence:0});
+    },
+
+    onSuccessNonExpected: function(response)
+    {
+        TestEngine.test("non expected successCallback invoked", false);
+    },
+
+    onErrorExpected: function(response)
+    {
+        TestEngine.test("expected errorCallback invoked", true);
+        TestEngine.testPresence("error code", response.code);
+        TestEngine.test("Error number", response.code == TestCalendar.expectedErrorCode);
+    },
+
+    onSuccess: function(response)
+    {
+        TestEngine.test("Callback success", true);
+    },
+
+    onErrorCb: function(response)
+    {
+        TestEngine.logErr("errorCallback invoked [" + response.code + ']');
+    },
+
+    //Cal001
+    test_modulePresence: function()
+    {
+        TestEngine.test("Calendar manager presence", deviceapis.pim.calendar);
+    },
+    //Cal002
+    test_calendarManagerConstants: function()
+    {
+        TestEngine.test("test property SIM_CALENDAR", deviceapis.pim.calendar.SIM_CALENDAR === 0);
+        TestEngine.test("test property DEVICE_CALENDAR", deviceapis.pim.calendar.DEVICE_CALENDAR === 1);
+        TestEngine.test("test property NO RECURRENCE", deviceapis.pim.calendar.NO_RECURRENCE === 0);
+        TestEngine.test("test property DAILY RECURENCE", deviceapis.pim.calendar.DAILY_RECURRENCE === 1);
+        TestEngine.test("test property WEEKLY RECURRENCE", deviceapis.pim.calendar.WEEKLY_RECURRENCE === 2);
+        TestEngine.test("test property MONTHLY RECURRENCE", deviceapis.pim.calendar.MONTHLY_RECURRENCE === 3);
+        TestEngine.test("test property YEARLY_RECURRENCE", deviceapis.pim.calendar.YEARLY_RECURRENCE === 4);
+        TestEngine.test("test property TENTATIVE_STATUS", deviceapis.pim.calendar.TENTATIVE_STATUS === 0);
+        TestEngine.test("test property CONFIRMED STATUS", deviceapis.pim.calendar.CONFIRMED_STATUS === 1);
+        TestEngine.test("test property CANCELED STATUS", deviceapis.pim.calendar.CANCELLED_STATUS === 2);
+        TestEngine.test("test property ALARM", deviceapis.pim.calendar.NO_ALARM === 0);
+        TestEngine.test("test property SILENT_ALARM", deviceapis.pim.calendar.SILENT_ALARM === 1);
+        TestEngine.test("test property SOUND_ALARM", deviceapis.pim.calendar.SOUND_ALARM === 2);
+    },
+
+    //Cal003
+    test_getCalendar: function()
+    {
+        function onSuccessGetCalendar(response)
+        {
+            TestEngine.test("Found calendars", response.length > 0);
+            TestCalendar.calendar=response[0];
+        }
+        function onErrorCb(response)
+        {
+            TestEngine.test("getCalendars error callback", false);
+            TestEngine.log("error callback invoked with code " +response.code);
+        }
+
+        var cbObj = TestEngine.registerCallback("getCalendars",
+            onSuccessGetCalendar,
+            onErrorCb);
+        deviceapis.pim.calendar.getCalendars(cbObj.successCallback, cbObj.errorCallback);
+    },
+
+    //Cal004
+    test_getCalendarNoCallbacks: function()
+    {
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(null);
+            }
+        );
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(undefined);
+            }
+        );
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(null, null);
+            }
+        );
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(undefined, undefined);
+            }
+        );
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(null, undefined);
+            }
+        );
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(undefined, null);
+            }
+        );
+    },
+
+    //Cal005
+    test_getCalendarInvalidCallbacks: function()
+    {
+        function onError(error)
+        {
+            TestEngine.test("getCalendars()", (error.code == INVALID_VALUES_ERR));
+        }
+        function onUnexpectedCallback()
+        {
+            TestEngine.test("getCalendars() unexpected callback", false);
+        }
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars");
+
+        var cbObj = TestEngine.registerCallback("getCalendars", null, onError);
+        deviceapis.pim.calendar.getCalendars(null, cbObj.errorCallback);
+
+        cbObj = TestEngine.registerCallback("getCalendars", null, onError);
+        deviceapis.pim.calendar.getCalendars(undefined, cbObj.errorCallback);
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", onUnexpectedCallback, 2);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", onUnexpectedCallback, "test2");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", 2, onUnexpectedCallback);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", "test2", onUnexpectedCallback);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", 2, null);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", "test2", undefined);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", 2);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", "test2");
+    },
+
+    //Cal006
+    test_calendarMethodsPresence: function()
+    {
+        TestEngine.testPresence("calendar.createEvent presence", TestCalendar.calendar.createEvent);
+        TestEngine.testPresence("calendar.addEvent presence", TestCalendar.calendar.addEvent);
+        TestEngine.testPresence("calendar.updateEvent presence", TestCalendar.calendar.updateEvent);
+        TestEngine.testPresence("calendar.deleteEvent presence", TestCalendar.calendar.deleteEvent);
+        TestEngine.testPresence("calendar.findEvents presence", TestCalendar.calendar.findEvents);
+    },
+
+    //Cal007
+    test_getCalendarName: function()
+    {
+        var cName = TestCalendar.calendar.name;
+        TestEngine.test("test getName", isString(cName) && cName.length > 0);
+        TestEngine.log("calendar name: " + cName);
+    },
+
+    //Cal008
+    test_getCalendarType: function ()
+    {
+        var cType = TestCalendar.calendar.type;
+        TestEngine.test("test getType", cType === deviceapis.pim.calendar.SIM_CALENDAR ||
+                                        cType === deviceapis.pim.calendar.DEVICE_CALENDAR);
+        TestEngine.log("calendar type: " + cType);
+
+    },
+
+    //Cal009
+    test_createEmptyEvent: function()
+    {
+        var event = TestCalendar.calendar.createEvent();
+        TestEngine.test("event created", isObject(event));
+    },
+
+    //Cal010
+    test_eventAttributes: function()
+    {
+        var event = TestCalendar.calendar.createEvent();
+        TestEngine.test("test attribute id", isString(event.id) || isNull(event.id) || isUndefineD(event.id));
+        var oldId = event.id;
+        event.id = "test" + oldId;
+        TestEngine.test("attribute id is read only", event.id === oldId);
+        TestEngine.test("test attribute description", isString(event.description));
+        TestEngine.test("test attribute summary", isString(event.summary));
+        TestEngine.test("test attribute startTime", isDate(event.startTime));
+        TestEngine.test("test attribute duration", isNumber(event.duration));
+        TestEngine.test("test attribute location", isString(event.location));
+        TestEngine.test("test attribute categories", isObject(event.categories) && event.categories.length == 0);
+        TestEngine.test("test attribute recurrence", isNumber(event.recurrence) && event.recurrence === deviceapis.pim.calendar.NO_RECURRENCE);
+        TestEngine.test("test attribute expires", event.expires === null);
+        TestEngine.test("test attribute interval", isNumber(event.interval));
+        TestEngine.test("test attribute status", isNumber(event.status) && event.status === deviceapis.pim.calendar.CONFIRMED_STATUS);
+        TestEngine.test("test attribute alarmTrigger", isNumber(event.alarmTrigger) && event.alarmTrigger === 0);
+        TestEngine.test("test attribute alarmType", isNumber(event.alarmType) && event.alarmType === deviceapis.pim.calendar.NO_ALARM);
+    },
+
+    //Cal011
+    test_createEvent: function()
+    {
+        var eventProp = {
+                description: 'Event created to test event creation',
+                summary: 'Test Event 1',
+                startTime: new Date(2009, 3, 30, 10, 0),
+                duration: 60,
+                location: 'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.DAILY_RECURRENCE,
+                expires: new Date(2009, 4, 30, 10, 0),
+                interval: 2,
+                status: deviceapis.pim.calendar.CANCELLED_STATUS,
+                alarmTrigger: -5,
+                alarmType: deviceapis.pim.calendar.SILENT_ALARM
+            };
+
+        var newEvent = TestCalendar.calendar.createEvent(eventProp);
+
+        TestEngine.test("event with param created ", newEvent);
+        TestEngine.test("correct description", newEvent.description === eventProp.description);
+        TestEngine.test("correct summary", newEvent.summary === eventProp.summary);
+        TestEngine.test("correct startTime", newEvent.startTime.toString() === eventProp.startTime.toString());
+        TestEngine.test("correct duration", newEvent.duration === eventProp.duration);
+        TestEngine.test("correct location", newEvent.location === eventProp.location);
+        TestEngine.test("correct categories", newEvent.categories.length === eventProp.categories.length &&
+                                              newEvent.categories[0] === eventProp.categories[0]);
+        TestEngine.test("correct recurrence", newEvent.recurrence === eventProp.recurrence);
+        TestEngine.test("correct expires", newEvent.expires.toString() === eventProp.expires.toString());
+        TestEngine.test("correct interval", newEvent.interval === eventProp.interval);
+        TestEngine.test("correct status", newEvent.status === eventProp.status);
+        TestEngine.test("correct alarmTrigger", newEvent.alarmTrigger === eventProp.alarmTrigger);
+        TestEngine.test("correct alarmType", newEvent.alarmType === eventProp.alarmType);
+
+    },
+
+    //this function is called from test_addEvent1, test_addEvent2 ...
+    addEvent: function(newEvent)
+    {
+        var event = newEvent;
+        var num_events;
+
+        function onErrorCb(response)
+        {
+            TestEngine.logErr("errorCallback invoked [" + response.code + ']');
+            TestEngine.test("add event", false);
+        }
+
+        function onSuccessAddEventCountAfter(response)
+        {
+            TestEngine.log("There is " + response.length +" events");
+            TestEngine.log("added event's id " + event.id);
+            TestEngine.test("Number of events increased", num_events + 1 == response.length);
+            var eventValidated = false;
+            for (var i in response) {
+                if (event.id != response[i].id) {
+                    continue;
+                }
+                TestEngine.test("description the same", response[i].description === event.description);
+                TestEngine.test("summary the same", response[i].summary === event.summary);
+                TestEngine.test("startTime the same", response[i].startTime.toString() === event.startTime.toString());
+                TestEngine.test("duration the same", response[i].duration === event.duration);
+                TestEngine.test("location the same", response[i].location === event.location);
+                TestEngine.test("categories the same", response[i].categories.length === event.categories.length);
+                TestEngine.test("recurrence the same", response[i].recurrence === event.recurrence);
+                TestEngine.test("expires the same", isNull(event.expires) ||
+                                                    response[i].expires.toString() === event.expires.toString());
+                TestEngine.test("interval the same", response[i].interval === event.interval);
+                TestEngine.test("status the same", response[i].status === event.status);
+                TestEngine.test("alarmTrigger the same, " + response[i].alarmTrigger, response[i].alarmTrigger === event.alarmTrigger);
+                TestEngine.test("alarmType the same", response[i].alarmType === event.alarmType);
+                eventValidated = true;
+            }
+            TestEngine.test("Event has been validated", eventValidated)
+            num_events=null;
+        }
+
+        function onSuccessAddEventAdd(response)
+        {
+            TestEngine.log("event added");
+            //count the number of events
+            TestEngine.log("counting existing events");
+            var objCb = TestEngine.registerCallback("onSuccessAddEventAdd",
+                onSuccessAddEventCountAfter, onErrorCb);
+            TestCalendar.calendar.findEvents(objCb.successCallback,
+                objCb.errorCallback);
+        }
+
+        function onSuccessAddEventCountBefore(response)
+        {
+            TestEngine.log("events counted");
+            //save current number of events
+            num_events = response.length;
+            TestEngine.log("There is " + num_events +" events");
+            TestEngine.log("adding new event");
+            //add new event
+            var objCb = TestEngine.registerCallback("onSuccessAddEventCountBefore",
+                onSuccessAddEventAdd, onErrorCb);
+            TestCalendar.calendar.addEvent(objCb.successCallback,
+                objCb.errorCallback,
+                event);
+        }
+
+        //save current number of events
+        TestEngine.log("counting existing events");
+        var objCb = TestEngine.registerCallback("findEvents",
+            onSuccessAddEventCountBefore,
+            onErrorCb);
+        TestCalendar.calendar.findEvents(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal012
+    test_addEvent1: function()
+    {
+        TestEngine.log("creating new event");
+        var event = TestCalendar.calendar.createEvent();
+        TestEngine.log("new event created");
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal013
+    test_addEvent2: function()
+    {
+        TestEngine.log("creating new event");
+        var event = TestCalendar.calendar.createEvent({
+                description:'Event created to test event creation',
+                summary:'Test Event 2',
+                startTime: new Date(2010, 11, 30, 10, 0),
+                duration: 15,
+                location:'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.DAILY_RECURRENCE,
+                expires: null,
+                interval: 1,
+                status: deviceapis.pim.calendar.TENTATIVE_STATUS,
+                alarmTrigger: 10,
+                alarmType: deviceapis.pim.calendar.SILENT_ALARM
+            });
+        TestEngine.log("new event created");
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal014
+    test_addEvent3: function()
+    {
+        TestEngine.log("creating new event");
+        var event = TestCalendar.calendar.createEvent({
+                description:'Event created to test event creation',
+                summary:'Test Event 3',
+                startTime: new Date(2010, 11, 30, 10, 0),
+                duration: 2,
+                location:'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.WEEKLY_RECURRENCE,
+                expires: new Date(2011, 11, 30, 10, 0),
+                interval: 1,
+                status: deviceapis.pim.calendar.CANCELLED_STATUS,
+                alarmTrigger: 0,
+                alarmType: deviceapis.pim.calendar.SOUND_ALARM
+            });
+        TestEngine.log("new event created");
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal015
+    test_addEvent4: function()
+    {
+        var event = TestCalendar.calendar.createEvent({
+                description:'Event created to test event creation',
+                summary:'Test Event 4',
+                startTime: new Date(2010, 11, 30, 10, 0),
+                duration: 60,
+                location:'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.NO_RECURRENCE,
+                expires: null,
+                interval: 1,
+                status: deviceapis.pim.calendar.CONFIRMED_STATUS,
+                alarmTrigger: -15,
+                alarmType: deviceapis.pim.calendar.NO_ALARM
+            });
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal016
+    test_addEvent5: function()
+    {
+        var event = TestCalendar.calendar.createEvent({
+                description:'Event created to test event creation',
+                summary:'Test Event 5',
+                startTime: new Date(2010, 11, 30, 10, 0),
+                duration: 60,
+                location:'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.MONTHLY_RECURRENCE,
+                expires: null,
+                interval: 1,
+                status: deviceapis.pim.calendar.CONFIRMED_STATUS,
+                alarmTrigger: -15,
+                alarmType: deviceapis.pim.calendar.NO_ALARM
+            });
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal017
+    test_addEvent6: function()
+    {
+        var event = TestCalendar.calendar.createEvent({
+                description:'Event created to test event creation',
+                summary:'Test Event 6',
+                startTime: new Date(2010, 11, 30, 10, 0),
+                duration: 60,
+                location:'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.YEARLY_RECURRENCE,
+                expires: null,
+                interval: 1,
+                status: deviceapis.pim.calendar.CONFIRMED_STATUS,
+                alarmTrigger: -15,
+                alarmType: deviceapis.pim.calendar.NO_ALARM
+            });
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal019
+    test_addEventNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent");
+    },
+
+    //Cal020
+    test_addEventInvalidCallbacksParams: function()
+    {
+        function onError(error)
+        {
+            TestEngine.test("addEvent()", (error.code == INVALID_VALUES_ERR));
+        }
+        function onUnexpectedCallback()
+        {
+            TestEngine.test("addEvent() unexpected callback", false);
+        }
+
+        var event = TestCalendar.createTestEvent();
+
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, undefined, event);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, undefined, event);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, null, event);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, null, event);
+        });
+
+        var cbObj = TestEngine.registerCallback("addEvent()", null, onError);
+        deviceapis.pim.calendar.getCalendars(null, cbObj.errorCallback, event);
+
+        cbObj = TestEngine.registerCallback("addEvent()", null, onError);
+        deviceapis.pim.calendar.getCalendars(undefined, cbObj.errorCallback, event);
+
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, undefined, null);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, undefined, undefined);
+        });
+
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, null, null);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, null, undefined);
+        });
+
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, undefined, null);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, undefined, undefined);
+        });
+
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, null, null);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, null, undefined);
+        });
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", 1, 1, null);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", "test", "test", null);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", 1, 1, undefined);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", "test", "test", undefined);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", 1, 1, event);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", "test", "test", event);
+    },
+
+    //Cal021
+    test_addEventWrongEventParam: function()
+    {
+        function onError(error)
+        {
+            TestEngine.test("addEvent()", (error.code == INVALID_VALUES_ERR));
+        }
+
+        function onSuccessNonExpected()
+        {
+            TestEngine.test("addEvent() non expected successCallback invoked", false);
+        }
+
+        function onUnexpectedCallback()
+        {
+            TestEngine.test("addEvent() unexpected callback", false);
+        }
+
+        var cbObj = TestEngine.registerCallback("addEvent()", onSuccessNonExpected, onError);
+        TestCalendar.calendar.addEvent(cbObj.successCallback, cbObj.errorCallback, null);
+
+        cbObj = TestEngine.registerCallback("addEvent()", onSuccessNonExpected, onError);
+        TestCalendar.calendar.addEvent(cbObj.successCallback, cbObj.errorCallback, undefined);
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent",
+            onUnexpectedCallback, onUnexpectedCallback, 22);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent",
+            onUnexpectedCallback, onUnexpectedCallback, "test");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent",
+            onUnexpectedCallback, onUnexpectedCallback);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent",
+            onUnexpectedCallback, onUnexpectedCallback, new Date());
+    },
+
+    //Cal022
+    test_findAllEvents: function()
+    {
+        function onSuccessFindAllEvents(response)
+        {
+            TestEngine.test("Find all events", response.length > 0);
+        }
+
+        function onErrorCb()
+        {
+            TestEngine.test("Find all events", false);
+        }
+
+        var objCb = TestEngine.registerCallback("findEvents",
+            onSuccessFindAllEvents,
+            onErrorCb);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    //function called by following tests
+    test_FindEventsWithFilterSomeResults: function(filterEval)
+    {
+        function onSuccessFindAllEvents(response)
+        {
+            function onSuccessFindEventWithFilterSomeResults(response)
+            {
+                TestEngine.log("found events: " + response.length);
+                TestEngine.test("FindEvents with filter found results", response.length > 0);
+            }
+
+            function onErrorCb()
+            {
+                TestEngine.test("FindEvents error callback", false);
+            }
+
+            TestEngine.test("Found any event for tests", response.length > 0);
+            if (response.length > 0) {
+                eval(filterEval);
+                if (filter) {
+                    for(var i in filter) {
+                        TestEngine.log("  Filter: " + i + " : " + filter[i]);
+                    }
+                }
+                var objCb = TestEngine.registerCallback("findEvents",
+                    onSuccessFindEventWithFilterSomeResults,
+                    onErrorCb);
+                TestCalendar.calendar.findEvents(objCb.successCallback,
+                    objCb.errorCallback,
+                    filter);
+            }
+        }
+
+        function onErrorCb()
+        {
+            TestEngine.test("Find all events", false);
+        }
+
+        var objCb = TestEngine.registerCallback("findEvents",
+            onSuccessFindAllEvents,
+            onErrorCb);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback);
+        },
+
+    //Cal023
+    test_findEventsId: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {id: response[0].id}");
+    },
+
+    //Cal024
+    test_findEventsSummary: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {summary: response[0].summary}");
+    },
+
+    //Cal025
+    test_findEventsDescription: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {description: response[0].description}");
+    },
+
+    //Cal026
+    test_findEventsLocation: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {location: response[0].location}");
+    },
+
+    //Cal027
+    test_findEventsCategory: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {category: 'SPRC'}");
+    },
+
+    //Cal028
+    test_findEventsStatus: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {status: [response[0].status]}");
+    },
+
+    //Cal029
+    test_findEventsFullStartTime: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {initialStartDate: response[0].startTime, endStartDate: response[0].startTime}");
+    },
+
+    //Cal030
+    test_findEventsInitialStartDate: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {initialStartDate: response[0].startTime, endStartDate: null}");
+    },
+
+    //Cal031
+    test_findEventsEndStartDate: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {initialStartDate: null, endStartDate: response[0].startTime}");
+    },
+
+    //Cal032
+    test_findEventsEmptyFilter: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults("var filter = {}");
+    },
+
+    //function called by following tests
+    test_FindEventsWithFilterNoResults: function(filter)
+    {
+        function onSuccessFindEventWithFilterNoResults(response)
+        {
+            TestEngine.test("FindEvents with filter not found results", response.length == 0);
+        }
+
+        function onErrorCb()
+        {
+            TestEngine.test("FindEvents error callback", false);
+        }
+
+        if(filter) {
+            for(var i in filter) {
+                TestEngine.log("  Filter: " + i + " : " + filter[i]);
+            }
+        }
+        var objCb = TestEngine.registerCallback("findEvents",
+            onSuccessFindEventWithFilterNoResults,
+            onErrorCb);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback,
+            filter);
+    },
+
+    //Cal033
+    test_findEventsFullStartTimeNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {initialStartDate: new Date(1980, 11, 30, 1, 0),
+             endStartDate: new Date(1980, 11, 30, 23, 0)});
+    },
+
+    //Cal034
+    test_findEventsLocationNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {location:"non existing location"});
+    },
+
+    //Cal035
+    test_findEventsSummaryNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {summary:'non existing summary'});
+    },
+
+    //Cal036
+    test_findEventsDescriptionNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {description:'non existing description'});
+    },
+
+    //Cal037
+    test_findEventsIdNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {id:"2000000"});
+    },
+
+    //Cal038
+    test_findEventsCategoryNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {category:'non existing category'});
+    },
+
+    //Cal039
+    test_findEventsNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "findEvents");
+    },
+
+    //Cal040
+    test_findEventsNoCallbacksParams: function()
+    {
+        testNoExceptionWithMessage("findEvents() null callbacks",
+            function()
+            {
+                TestCalendar.calendar.findEvents(null, null);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() undefined callbacks",
+            function()
+            {
+                TestCalendar.calendar.findEvents(undefined, undefined);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() undefined success callback, null error callback",
+            function()
+            {
+                TestCalendar.calendar.findEvents(undefined, null);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() null success callback, undefined error callback",
+            function()
+            {
+                TestCalendar.calendar.findEvents(null, undefined);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() undefined success callback, missing error callback",
+            function()
+            {
+                TestCalendar.calendar.findEvents(undefined);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() null success callback, missing error callback",
+            function()
+            {
+                TestCalendar.calendar.findEvents(null);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() null callbacks, empty filter",
+            function()
+            {
+                TestCalendar.calendar.findEvents(null, null, {});
+            }
+        );
+        testNoExceptionWithMessage("findEvents() undefined callbacks, empty filter",
+            function()
+            {
+                TestCalendar.calendar.findEvents(undefined, undefined, {});
+            }
+        );
+    },
+
+    //Cal041
+    test_findEventsWrongFilterParam: function()
+    {
+        function onSuccess(response)
+        {
+            TestEngine.test("findEvents() success callback invoked", true);
+        }
+
+        function onError(response)
+        {
+            TestEngine.test("findEvents() error callback invoked", false);
+        }
+
+        var objCb = TestEngine.registerCallback("Find events with undefined filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback, null);
+
+        objCb = TestEngine.registerCallback("Find events with undefined filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback, undefined);
+    },
+
+    //this function is called by following tests
+    updateEvent: function(newValues)
+    {
+        function onErrorCb()
+        {
+            TestEngine.test("Find all events", false);
+        }
+
+        function onSuccessFindAllEvents(response)
+        {
+            TestEngine.test("Find all events", response.length > 0);
+            if (response.length > 0) {
+                var event = response[0];
+                function onSuccessUpdateEvent1(response)
+                {
+                    TestEngine.log("updateEvent() success callback entered entered");
+
+                    function onSuccessUpdateEvent2(response)
+                    {
+                        TestEngine.test("found updated event", response.length > 0);
+                        if (response.length > 0) {
+                            var f_flag = 0;
+                            for (var i in response) {
+                                f_flag = 1;
+                                for (var j in newValues) {
+                                    if (isDate(newValues[j])) {
+                                        if (response[i][j].toString() != newValues[j].toString()) {
+                                            f_flag = 0;
+                                            break;
+                                        }
+                                    }
+                                    else if (isArray(newValues[j]))
+                                    {
+                                        if (response[i][j].length != newValues[j].length ||
+                                            response[i][j][0] != newValues[j][0]) {
+                                            f_flag = 0;
+                                            break;
+                                        }
+                                    }
+                                    else {
+                                        if (response[i][j] !== newValues[j]) {
+                                            if (j == "expires" && newValues[j] == null) {
+                                                //expires date with null should not be checked
+                                                TestEngine.log("dupa " + j);
+                                                continue;
+                                            }
+                                            f_flag = 0;
+                                            break;
+                                        }
+                                    }
+                                }
+                                if (f_flag == 1) {
+                                    break;
+                                }
+                            }
+                            TestEngine.test("Updated event validated successfully", f_flag == 1);
+                        }
+                        else {
+                            TestEngine.test("Updated events found", false);
+                        }
+                    }
+
+                    //find updated event
+                    var objCb = TestEngine.registerCallback("findEvents",
+                        onSuccessUpdateEvent2,
+                        onErrorCb);
+                    TestCalendar.calendar.findEvents(objCb.successCallback,
+                        objCb.errorCallback, {id: event.id});
+                }
+                for (var i in newValues) {
+                    TestEngine.log("update property: " + i + ", new value: " + newValues[i]);
+                    event[i] = newValues[i];
+                }
+                var objCb = TestEngine.registerCallback("updateEvent",
+                    onSuccessUpdateEvent1,
+                    onErrorCb);
+                TestCalendar.calendar.updateEvent(objCb.successCallback,
+                    objCb.errorCallback,
+                    event);
+            }
+        }
+
+        var objCb = TestEngine.registerCallback("findEvents",
+            onSuccessFindAllEvents,
+            onErrorCb);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    //Cal042
+    test_updateEvent1: function()
+    {
+        var newValues = {
+                description:'updated description 1',
+                summary:'Updated Test Event 1',
+                startTime: new Date(2011, 01, 01, 01, 01),
+                duration: 11,
+                location:'London 1',
+                categories: ["SPRC 1"],
+                recurrence: deviceapis.pim.calendar.NO_RECURRENCE,
+                expires: null,
+                interval: 1,
+                status: deviceapis.pim.calendar.TENTATIVE_STATUS,
+                alarmTrigger: 1,
+                alarmType: deviceapis.pim.calendar.NO_ALARM
+            };
+        TestCalendar.updateEvent(newValues)
+    },
+
+    //Cal043
+    test_updateEvent2: function()
+    {
+        var newValues = {
+                description:'updated description 2',
+                summary:'Updated Test Event 2',
+                startTime: new Date(2012, 02, 02, 02, 02),
+                duration: 22,
+                location:'London 2',
+                categories: ["SPRC 2"],
+                recurrence: deviceapis.pim.calendar.DAILY_RECURRENCE,
+                expires: null,
+                interval: 2,
+                status: deviceapis.pim.calendar.CONFIRMED_STATUS,
+                alarmTrigger: 2,
+                alarmType: deviceapis.pim.calendar.SILENT_ALARM
+            };
+        TestCalendar.updateEvent(newValues)
+    },
+
+    //Cal044
+    test_updateEvent3: function()
+    {
+        var newValues = {
+                description:'updated description 3',
+                summary:'Updated Test Event 3',
+                startTime: new Date(2013, 03, 03, 03, 03),
+                duration: 33,
+                location:'London 3',
+                categories: [],
+                recurrence: deviceapis.pim.calendar.WEEKLY_RECURRENCE,
+                expires: null,
+                interval: 3,
+                status: deviceapis.pim.calendar.CANCELLED_STATUS,
+                alarmTrigger: 3,
+                alarmType: deviceapis.pim.calendar.SOUND_ALARM
+            };
+        TestCalendar.updateEvent(newValues)
+    },
+
+    //Cal045
+    test_updateEvent4: function()
+    {
+        var newValues = {
+                description:'updated description 4',
+                summary:'Updated Test Event 4',
+                startTime: new Date(2014, 04, 04, 04, 04),
+                duration: 44,
+                location:'London 4',
+                categories: ["SPRC 4"],
+                recurrence: deviceapis.pim.calendar.MONTHLY_RECURRENCE,
+                expires: new Date(2015, 03, 03, 03, 03),
+                interval: 4,
+                status: deviceapis.pim.calendar.CANCELLED_STATUS,
+                alarmTrigger: 4,
+                alarmType: deviceapis.pim.calendar.SOUND_ALARM
+            };
+        TestCalendar.updateEvent(newValues)
+    },
+
+    //Cal046
+    test_updateEvent5: function()
+    {
+        var newValues = {
+                description:'updated description 5',
+                summary:'Updated Test Event 5',
+                startTime: new Date(2015, 05, 05, 05, 05),
+                duration: 55,
+                location:'London 5',
+                categories: ["SPRC 5"],
+                recurrence: deviceapis.pim.calendar.YEARLY_RECURRENCE,
+                expires: new Date(2016, 03, 03, 03, 03),
+                interval: 5,
+                status: deviceapis.pim.calendar.CANCELLED_STATUS,
+                alarmTrigger: -5,
+                alarmType: deviceapis.pim.calendar.SOUND_ALARM
+            };
+        TestCalendar.updateEvent(newValues)
+    },
+
+    //Cal047
+    test_updateEventNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent");
+    },
+
+    //Cal048
+    test_updateEventNullCallbacksParams: function()
+    {
+        var event = TestCalendar.createTestEvent();
+        testNoExceptionWithMessage("updateEvent() null callbacks",
+            function()
+            {
+                TestCalendar.calendar.updateEvent(null, null, event);
+            }
+        );
+        testNoExceptionWithMessage("updateEvent() undefined callbacks",
+            function()
+            {
+                TestCalendar.calendar.updateEvent(undefined, undefined, event);
+            }
+        );
+        testNoExceptionWithMessage("updateEvent() undefined success callback, null error callback",
+            function()
+            {
+                TestCalendar.calendar.updateEvent(undefined, null, event);
+            }
+        );
+        testNoExceptionWithMessage("updateEvent() null success callback, undefined error callback",
+            function()
+            {
+                TestCalendar.calendar.updateEvent(null, undefined, event);
+            }
+        );
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent", 1, undefined, event);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent", "test", undefined, event);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent", undefined, 1, event);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent", undefined, "test", event);
+    },
+
+    //Cal049
+    test_updateEventWrongEventParam: function()
+    {
+        function onUnexpectedCallback()
+        {
+            TestEngine.test("updateEvent() unexpected callback", false);
+        }
+        function onSuccess()
+        {
+            TestEngine.test("updateEvent() unexpected success callback invoked", false);
+        }
+
+        function onError(response)
+        {
+            TestEngine.test("updateEvent() error callback invoked", response.code == INVALID_VALUES_ERR);
+        }
+
+        var objCb = TestEngine.registerCallback("Update event with undefined filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.updateEvent(objCb.successCallback,
+            objCb.errorCallback, null);
+
+        objCb = TestEngine.registerCallback("Update event with undefined filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.updateEvent(objCb.successCallback,
+            objCb.errorCallback, undefined);
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent",
+            onUnexpectedCallback, onUnexpectedCallback, 22);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent",
+            onUnexpectedCallback, onUnexpectedCallback, "test");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent",
+            onUnexpectedCallback, onUnexpectedCallback);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent",
+            onUnexpectedCallback, onUnexpectedCallback, new Date());
+    },
+
+    //Cal050
+    test_deleteEvent: function()
+    {
+        var foundEventsFlag = 0;
+
+        function onError()
+        {
+            TestEngine.test("deleteEvent() error callback invoked", false);
+        }
+
+        function onSuccessDeleteEvent()
+        {
+            TestEngine.test("deleteEvent() success callback invoked", true);
+            findEvents();
+        }
+
+        function onSuccessFindEvents(response)
+        {
+            TestEngine.log("deleteEvent() callback entered");
+            if (foundEventsFlag == 0) {
+                //this validation is only for the first call
+                TestEngine.test("Events for delete found", response.length > 0);
+            }
+            foundEventsFlag = 1;
+            if (response.length > 0) {
+                var objCb = TestEngine.registerCallback("deleteEvents",
+                    onSuccessDeleteEvent,
+                    onError);
+                TestCalendar.calendar.deleteEvent(objCb.successCallback,
+                    objCb.errorCallback, response[0].id);
+            }
+            else {
+                TestEngine.test("All events deleted", true);
+            }
+        }
+
+        function findEvents()
+        {
+            //find all events
+            var objCb = TestEngine.registerCallback("deleteEvent",
+                onSuccessFindEvents,
+                onError);
+            TestCalendar.calendar.findEvents(objCb.successCallback,
+                objCb.errorCallback);
+        }
+        //recursively delete all events
+        findEvents();
+    },
+
+    //Cal051
+    test_deleteEventNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent");
+    },
+
+    //Cal052
+    test_deleteEventNullCallbacksParams: function()
+    {
+        testNoExceptionWithMessage("deleteEvent() null callbacks",
+            function()
+            {
+                TestCalendar.calendar.deleteEvent(null, null, "1");
+            }
+        );
+        testNoExceptionWithMessage("deleteEvent() undefined callbacks",
+            function()
+            {
+                TestCalendar.calendar.deleteEvent(undefined, undefined, event);
+            }
+        );
+        testNoExceptionWithMessage("deleteEvent() undefined success callback, null error callback",
+            function()
+            {
+                TestCalendar.calendar.deleteEvent(undefined, null, event);
+            }
+        );
+        testNoExceptionWithMessage("deleteEvent() null success callback, undefined error callback",
+            function()
+            {
+                TestCalendar.calendar.deleteEvent(null, undefined, event);
+            }
+        );
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent", 1, undefined, "1");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent", "test", undefined, "1");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent", undefined, 1, "1");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent", undefined, "test", "1");
+    },
+
+    //Cal053
+    test_deleteEventWrongEventParam: function()
+    {
+        function onUnexpectedCallback()
+        {
+            TestEngine.test("deleteEvent() unexpected callback", false);
+        }
+        function onSuccess()
+        {
+            TestEngine.test("deleteEvent() unexpected success callback invoked", false);
+        }
+
+        function onError(response)
+        {
+            TestEngine.test("deleteEvent() error callback invoked", response.code == NOT_FOUND_ERR);
+        }
+
+        var objCb = TestEngine.registerCallback("Delete event with null filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.deleteEvent(objCb.successCallback,
+            objCb.errorCallback, null);
+
+        objCb = TestEngine.registerCallback("Delete event with undefined filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.deleteEvent(objCb.successCallback,
+            objCb.errorCallback, undefined);
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent",
+                onUnexpectedCallback, onUnexpectedCallback, 22);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent",
+                onUnexpectedCallback, onUnexpectedCallback);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent",
+                onUnexpectedCallback, onUnexpectedCallback, new Date());
+    },
+
+    test_concatCategoryArray: function()
+    {
+        var category1 = "SPRC category";
+        var category2 = "test";
+        var category3 = "test2";
+        var category4 = "test aaa";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        TestEngine.test("category array has one element", event.categories.length === 1);
+        TestEngine.test("category array has proper value", event.categories[0] === category1);
+        var concatArray = event.categories.concat([category2, category3]);
+        TestEngine.test("concatenated category array has three elements", concatArray.length === 3);
+        TestEngine.test("concatenated category array has proper value [0]", concatArray[0] === category1);
+        TestEngine.test("concatenated category array has proper value [1]", concatArray[1] === category2);
+        TestEngine.test("concatenated category array has proper value [2]", concatArray[2] === category3);
+        concatArray = event.categories.concat([category2, category3], [category4]);
+        TestEngine.test("concatenated category array has four elements", concatArray.length === 4);
+        TestEngine.test("concatenated category array has proper value [0]", concatArray[0] === category1);
+        TestEngine.test("concatenated category array has proper value [1]", concatArray[1] === category2);
+        TestEngine.test("concatenated category array has proper value [2]", concatArray[2] === category3);
+        TestEngine.test("concatenated category array has proper value [3]", concatArray[3] === category4);
+        TestEngine.test("category array still has one element", event.categories.length === 1);
+    },
+
+    test_joinCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        event.categories[1] = category2;
+        event.categories[2] = category3;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("joining with default separator", event.categories.join()  === category1 + "," + category2 + "," + category3);
+        TestEngine.test("joining with space separator", event.categories.join(" ") === category1 + " " + category2 + " " + category3);
+        TestEngine.test("joining with longer string separator", event.categories.join(" how about ") === category1 + " how about " + category2 + " how about " + category3);
+        TestEngine.test("category array still has three elements", event.categories.length === 3);
+    },
+
+    test_popCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        event.categories[1] = category2;
+        event.categories[2] = category3;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("poped element has correct value", event.categories.pop() === category3);
+        TestEngine.test("category array has three elements", event.categories.length === 2);
+        TestEngine.test("poped element has correct value", event.categories.pop() === category2);
+        TestEngine.test("category array has three elements", event.categories.length === 1);
+        TestEngine.test("poped element has correct value", event.categories.pop() === category1);
+        TestEngine.test("category array has three elements", event.categories.length === 0);
+        TestEngine.test("poped element has correct value", event.categories.pop() === undefined);
+        TestEngine.test("poped element has correct value", event.categories.pop() === undefined);
+    },
+
+    test_pushCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories.push(category1);
+        event.categories.push(category2);
+        event.categories.push(category3);
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("array element [0] has correct value", event.categories[0] === category1);
+        TestEngine.test("array element [1] has correct value", event.categories[1] === category2);
+        TestEngine.test("array element [2] has correct value", event.categories[2] === category3);
+    },
+
+    test_reverseCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var category4 = "category3";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories.push(category1);
+        event.categories.push(category2);
+        event.categories.push(category3);
+        event.categories.push(category4);
+        event.categories.reverse();
+        TestEngine.test("category array has four elements", event.categories.length === 4);
+        TestEngine.test("array element [0] has correct value", event.categories[0] === category4);
+        TestEngine.test("array element [1] has correct value", event.categories[1] === category3);
+        TestEngine.test("array element [2] has correct value", event.categories[2] === category2);
+        TestEngine.test("array element [3] has correct value", event.categories[3] === category1);
+    },
+
+    test_shiftCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        event.categories[1] = category2;
+        event.categories[2] = category3;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("shifted element has correct value", event.categories.shift() === category1);
+        TestEngine.test("category array has three elements", event.categories.length === 2);
+        TestEngine.test("shifted element has correct value", event.categories.shift() === category2);
+        TestEngine.test("category array has three elements", event.categories.length === 1);
+        TestEngine.test("shifted element has correct value", event.categories.shift() === category3);
+        TestEngine.test("category array has three elements", event.categories.length === 0);
+        TestEngine.test("shifted element has correct value", event.categories.shift() === undefined);
+        TestEngine.test("shifted element has correct value", event.categories.shift() === undefined);
+    },
+
+    test_sliceCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        event.categories[1] = category2;
+        event.categories[2] = category3;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        var slice = event.categories.slice(0, 2);
+        TestEngine.test("slice array has correct number of elements", slice.length === 3);
+        slice = event.categories.slice(0, 1);
+        TestEngine.test("slice array has correct number of elements", slice.length === 2);
+        slice = event.categories.slice(0, 0);
+        TestEngine.test("slice array has correct number of elements", slice.length === 1);
+        slice = event.categories.slice(0);
+        TestEngine.test("slice array has correct number of elements", slice.length === 3);
+        slice = event.categories.slice(1);
+        TestEngine.test("slice array has correct number of elements", slice.length === 2);
+        slice = event.categories.slice(2);
+        TestEngine.test("slice array has correct number of elements", slice.length === 1);
+        slice = event.categories.slice(3);
+        TestEngine.test("slice array has correct number of elements", slice.length === 0);
+    },
+
+    test_sortCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category3;
+        event.categories[1] = category2;
+        event.categories[2] = category1;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        event.categories.sort();
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("array element [0] has correct value", event.categories[0] === category1);
+        TestEngine.test("array element [1] has correct value", event.categories[1] === category2);
+        TestEngine.test("array element [2] has correct value", event.categories[2] === category3);
+    },
+
+    test_toStringCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        event.categories[1] = category2;
+        event.categories[2] = category3;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("toString return correct value", event.categories.join() === category1 + "," + category2 + "," + category3);
+    }
+};
+//=============================================================================
+TestEngine.setTestSuiteName("[WAC2.0][Calendar]");
+////Cal001
+//TestEngine.addTest(true,TestCalendar.test_modulePresence, "[WAC2.0][Calendar] Test calendar module presence");
+////Cal002
+//TestEngine.addTest(true,TestCalendar.test_calendarManagerConstants, "[WAC2.0][Calendar] Calendar manager constants");
+////Cal003
+TestEngine.addTest(true,TestCalendar.test_getCalendar, "[WAC2.0][Calendar] Get calendar");
+////Cal004
+//TestEngine.addTest(true,TestCalendar.test_getCalendarNoCallbacks, "[WAC2.0][Calendar] Get calendar with no callbacks");
+////Cal005
+//TestEngine.addTest(true,TestCalendar.test_getCalendarInvalidCallbacks, "[WAC2.0][Calendar] Get calendar with invalid callbacks");
+////Cal006
+//TestEngine.addTest(true,TestCalendar.test_calendarMethodsPresence, "[WAC2.0][Calendar] Calendar methods presence");
+////Cal007
+//TestEngine.addTest(true,TestCalendar.test_getCalendarName, "[WAC2.0][Calendar] Get calendar name");
+////Cal008
+//TestEngine.addTest(true,TestCalendar.test_getCalendarType, "[WAC2.0][Calendar] Get calendar type");
+////Cal009
+//TestEngine.addTest(true,TestCalendar.test_createEmptyEvent, "[WAC2.0][Calendar] Create empty event");
+////Cal010
+//TestEngine.addTest(true,TestCalendar.test_eventAttributes, "[WAC2.0][Calendar] event attributes");
+////Cal011
+//TestEngine.addTest(true,TestCalendar.test_createEvent, "[WAC2.0][Calendar] Create event");
+//
+////Cal012
+//TestEngine.addTest(true,TestCalendar.test_addEvent1, "[WAC2.0][Calendar] Add event 1");
+////Cal013
+//TestEngine.addTest(true,TestCalendar.test_addEvent2, "[WAC2.0][Calendar] Add event 2");
+////Cal014
+//TestEngine.addTest(true,TestCalendar.test_addEvent3, "[WAC2.0][Calendar] Add event 3");
+////Cal015
+//TestEngine.addTest(true,TestCalendar.test_addEvent4, "[WAC2.0][Calendar] Add event 4");
+////Cal016
+//TestEngine.addTest(true,TestCalendar.test_addEvent5, "[WAC2.0][Calendar] Add event 5");
+////Cal017
+//TestEngine.addTest(true,TestCalendar.test_addEvent6, "[WAC2.0][Calendar] Add event 6");
+////Cal019
+//TestEngine.addTest(true,TestCalendar.test_addEventNoParams, "[WAC2.0][Calendar] Add event with no params");
+////Cal020
+//TestEngine.addTest(true,TestCalendar.test_addEventInvalidCallbacksParams, "[WAC2.0][Calendar] Add event with wrong callbacks");
+////Cal021
+//TestEngine.addTest(true,TestCalendar.test_addEventWrongEventParam, "[WAC2.0][Calendar] Add event with wrong event param");
+//
+////Cal022
+//TestEngine.addTest(true,TestCalendar.test_findAllEvents, "[WAC2.0][Calendar] Find all events");
+////Cal023
+//TestEngine.addTest(true,TestCalendar.test_findEventsId, "[WAC2.0][Calendar] Find events, filter: id");
+////Cal024
+//TestEngine.addTest(true,TestCalendar.test_findEventsSummary, "[WAC2.0][Calendar] Find events, filter: summary");
+////Cal025
+//TestEngine.addTest(true,TestCalendar.test_findEventsDescription, "[WAC2.0][Calendar] Find events, filter: description");
+////Cal026
+//TestEngine.addTest(true,TestCalendar.test_findEventsLocation, "[WAC2.0][Calendar] Find events, filter: location");
+////Cal027
+//TestEngine.addTest(true,TestCalendar.test_findEventsCategory, "[WAC2.0][Calendar] Find events, filter: category");
+////Cal028
+//TestEngine.addTest(true,TestCalendar.test_findEventsStatus, "[WAC2.0][Calendar] Find events, filter: status");
+////Cal029
+//TestEngine.addTest(true,TestCalendar.test_findEventsFullStartTime, "[WAC2.0][Calendar] Find events, filter: initialStartDate and endStartDate");
+////Cal030
+//TestEngine.addTest(true,TestCalendar.test_findEventsInitialStartDate, "[WAC2.0][Calendar] Find events, filter: initialStartDate");
+////Cal031
+//TestEngine.addTest(true,TestCalendar.test_findEventsEndStartDate, "[WAC2.0][Calendar] Find events, filter: endStartDate");
+////Cal032
+//TestEngine.addTest(true,TestCalendar.test_findEventsEmptyFilter, "[WAC2.0][Calendar] Find events, filter: empty filter");
+////Cal033
+//TestEngine.addTest(true,TestCalendar.test_findEventsFullStartTimeNoResults, "[WAC2.0][Calendar] Find events, no results, filter: initialStartDate and endStartDate");
+////Cal034
+//TestEngine.addTest(true,TestCalendar.test_findEventsLocationNoResults, "[WAC2.0][Calendar] Find events, no results, filter: location");
+////Cal035
+//TestEngine.addTest(true,TestCalendar.test_findEventsSummaryNoResults, "[WAC2.0][Calendar] Find events, no results, filter: summary");
+////Cal036
+//TestEngine.addTest(true,TestCalendar.test_findEventsDescriptionNoResults, "[WAC2.0][Calendar] Find events, no results, filter: description");
+////Cal037
+//TestEngine.addTest(true,TestCalendar.test_findEventsIdNoResults, "[WAC2.0][Calendar] Find events, no results, filter: id");
+////Cal038
+//TestEngine.addTest(true,TestCalendar.test_findEventsCategoryNoResults, "[WAC2.0][Calendar] Find events, no results, filter: category");
+////Cal039
+//TestEngine.addTest(true,TestCalendar.test_findEventsNoParams, "[WAC2.0][Calendar] Find events with no params");
+////Cal040
+//TestEngine.addTest(true,TestCalendar.test_findEventsNoCallbacksParams, "[WAC2.0][Calendar] Find events with no callbacks");
+////Cal041
+//TestEngine.addTest(true,TestCalendar.test_findEventsWrongFilterParam, "[WAC2.0][Calendar] Find events with wrong filter param");
+//
+////Cal042
+//TestEngine.addTest(true,TestCalendar.test_updateEvent1, "[WAC2.0][Calendar] Update event 1");
+////Cal043
+//TestEngine.addTest(true,TestCalendar.test_updateEvent2, "[WAC2.0][Calendar] Update event 2");
+////Cal044
+//TestEngine.addTest(true,TestCalendar.test_updateEvent3, "[WAC2.0][Calendar] Update event 3");
+////Cal045
+//TestEngine.addTest(true,TestCalendar.test_updateEvent4, "[WAC2.0][Calendar] Update event 4");
+////Cal046
+//TestEngine.addTest(true,TestCalendar.test_updateEvent5, "[WAC2.0][Calendar] Update event 5");
+////Cal047
+//TestEngine.addTest(true,TestCalendar.test_updateEventNoParams, "[WAC2.0][Calendar] Update event with no params");
+////Cal048
+//TestEngine.addTest(true,TestCalendar.test_updateEventNullCallbacksParams, "[WAC2.0][Calendar] Update event with wrong callbacks");
+////Cal049
+//TestEngine.addTest(true,TestCalendar.test_updateEventWrongEventParam, "[WAC2.0][Calendar] Update event with wrong event param");
+//
+////Cal050
+//TestEngine.addTest(true,TestCalendar.test_deleteEvent, "[WAC2.0][Calendar] Delete event");
+////Cal051
+//TestEngine.addTest(true,TestCalendar.test_deleteEventNoParams, "[WAC2.0][Calendar] Delete event with no params");
+////Cal052
+//TestEngine.addTest(true,TestCalendar.test_deleteEventNullCallbacksParams, "[WAC2.0][Calendar] Delete event with wrong callbacks");
+////Cal053
+//TestEngine.addTest(true,TestCalendar.test_deleteEventWrongEventParam, "[WAC2.0][Calendar] Delete event with wrong event param");
+//
+////Cal050
+//TestEngine.addTest(true,TestCalendar.test_concatCategoryArray, "[WAC2.0][Calendar] Concat category array");
+////Cal051
+//TestEngine.addTest(true,TestCalendar.test_joinCategoryArray, "[WAC2.0][Calendar] Join category array");
+////Cal052
+//TestEngine.addTest(true,TestCalendar.test_popCategoryArray, "[WAC2.0][Calendar] Pop category array");
+////Cal053
+//TestEngine.addTest(true,TestCalendar.test_pushCategoryArray, "[WAC2.0][Calendar] Push category array");
+////Cal054
+//TestEngine.addTest(true,TestCalendar.test_reverseCategoryArray, "[WAC2.0][Calendar] Reverse category array");
+////Cal055
+//TestEngine.addTest(true,TestCalendar.test_shiftCategoryArray, "[WAC2.0][Calendar] Shift category array");
+////Cal056
+//TestEngine.addTest(true,TestCalendar.test_sliceCategoryArray, "[WAC2.0][Calendar] Slice category array");
+////Cal057
+//TestEngine.addTest(true,TestCalendar.test_sortCategoryArray, "[WAC2.0][Calendar] Sort category array");
+////Cal058
+//TestEngine.addTest(true,TestCalendar.test_toStringCategoryArray, "[WAC2.0][Calendar] toString category array");
+
+//=============================================================================
+
+function testNoExceptionWithMessage(message, fun) {
+    var testResult = true;
+    try
+    {
+        fun();
+    }
+    catch (e)
+    {
+        testResult = false;
+    }
+    TestEngine.test(message, testResult);
+}
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestCamera.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestCamera.js
new file mode 100644 (file)
index 0000000..13adccd
--- /dev/null
@@ -0,0 +1,1191 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test for camera module classes.
+ *
+ * @author      Wojciech Bielawski (w.bielawski@samsung.com)
+ * @version     0.1
+ */
+
+var gcameras;
+var mainCamera;
+var callbackExecuted = false;
+var previewId = "cameraPreview";
+
+var VideoTime = 5000;
+
+TestEngine.setErrorType(Object);
+TestEngine.setErrorField('code');
+var TYPE_MISMATCH_ERR = 17;
+var INVALID_VALUES_ERR = 22;
+var SECURITY_ERR = 18;
+var NOT_FOUND_ERR = 8;
+
+
+/*
+ * Function to generate unique filename
+ */
+function GetFileName(prefix, suffix)
+{
+    var date = new Date();
+    var name = prefix + date.getTime() + suffix;
+    TestEngine.log(name);
+    return name;
+}
+
+function waitMs(ms)
+{
+    ms += new Date().getTime();
+    while (new Date() < ms){}
+}
+
+
+/* Cam001 */
+function TestGetCameras()
+{
+    var obj = TestEngine.registerCallback(
+        "getCameras",
+        function(cameras){
+            if (cameras.length > 0) {
+                gcameras = cameras;
+                mainCamera = cameras[0];
+                TestEngine.log("Cameras size: " + cameras.length);
+                TestEngine.test("Size of cameras array", cameras.length == 2);
+            } else {
+                TestEngine.logErr("No camera found");
+            }
+        },
+        function(err){
+            TestEngine.logErr("Get cameras failed. Exception code: " + err.code);
+        });
+    try {
+        deviceapis.camera.getCameras(obj.successCallback, obj.errorCallback);
+    } catch(e) {
+        TestEngine.logErr("Exception while getting cameras");
+    }
+}
+
+/* Cam002 */
+function TestCaseCameraArrayProperties()
+{
+    TestEngine.test("Camera array", isArray(gcameras));
+    TestEngine.test("Camera array length", gcameras.length == 2);
+}
+
+function TestJavaScript()
+{
+    try
+    {
+        var divElement = document.getElementById("video");
+        var para = document.createElement("p");
+        para.setAttribute("style","color:blue;");
+        var text = document.createTextNode("this is my text");
+        para.appendChild(text);
+        divElement.appendChild(para);
+    }
+    catch(e)
+    {
+        TestEngine.log("Exception: " + e);
+    }
+    TestEngine.log("Test finish");
+}
+
+/* Cam003 */
+function TestCameraFunctionality_PreviewStart()
+{
+    TestEngine.log("Create Preview");
+
+    function successCallback(obj)
+    {
+        try
+        {
+            TestEngine.test("Type of preview node", "object" === typeof(obj));
+            var divElement = document.getElementById("video");
+            TestEngine.test("Type of preview node parent", "object" === typeof(divElement));
+            divElement.appendChild(obj);
+            obj.id = previewId;
+            TestEngine.test("preview node id", previewId === obj.id);
+            obj.style.visibility = "visible";
+            TestEngine.test("Preview created", true);
+        }
+        catch(e)
+        {
+            TestEngine.test("Preview created", false);
+            TestEngine.logErr("exception: " + e);
+        }
+    }
+
+    function errorCallback()
+    {
+        TestEngine.test("Preview created", false);
+    }
+
+    try
+    {
+        var obj = TestEngine.registerCallback(
+                "createPreviewNode",
+                successCallback,
+                errorCallback);
+                gcameras[0].createPreviewNode(obj.successCallback, obj.errorCallback);
+    }
+    catch(e)
+    {
+        TestEngine.test("Preview created", false);
+        TestEngine.logErr("exception: " + e);
+    }
+}
+
+function TestCameraFunctionality_PreviewStop()
+{
+    function stopFunction()
+    {
+        TestEngine.log("stopping");
+        var divElement = document.getElementById("video");
+        var previewNode = document.getElementById(previewId);
+
+        TestEngine.test("Type of preview node parent", "object" === typeof(divElement));
+        TestEngine.test("Type of preview node parent", "object" === typeof(previewNode));
+
+        previewNode.style.visibility = "hidden";
+        divElement.removeChild(previewNode);
+
+        TestEngine.test("Preview removed", true);
+    }
+
+    var timeout = 5000;
+    TestEngine.log("preview will end in " + timeout + " miliseconds");
+    var obj = TestEngine.registerCallback(
+            "createPreviewNode",
+            stopFunction,
+            undefined);
+    setTimeout(obj.successCallback, timeout);
+}
+
+function TestCameraFunctionality_TakePicture()
+{
+    function success(filename)
+    {
+        TestEngine.log("filename = " + filename);
+        TestEngine.test("image captured", true)
+    }
+
+    function error(e)
+    {
+        TestEngine.test("image captured", false)
+    }
+
+    TestEngine.log("Take picutre");
+    var requestedFileName = GetFileName("images/test_photo_",".jpg");
+    var obj = TestEngine.registerCallback("captureImage", success, error);
+    gcameras[0].captureImage(obj.successCallback,
+                             obj.errorCallback,
+                             {destinationFilename:requestedFileName, highRes:false});
+}
+
+var callbackExecuted = false;
+function TestCameraFunctionality_Video()
+{
+    //wait for stabilization
+    waitMs(3000);
+
+    function success(filename)
+    {
+        TestEngine.test("video capture", true);
+        callbackExecuted = true;
+    }
+
+    function error(e)
+    {
+        TestEngine.test("video captured", false);
+        callbackExecuted = true;
+    }
+
+    function checkCompletness()
+    {
+        if(!callbackExecuted)
+        {
+            TestEngine.test("Video capture time out", false);
+        }
+    }
+
+    TestEngine.log("Video Recording");
+    var requestedFileName = GetFileName("videos/test_video_",".mp4");
+    var obj = TestEngine.registerCallback("captureVideo", success, error);
+    gcameras[0].startVideoCapture(obj.successCallback,
+                                  obj.errorCallback,
+                                  {destinationFilename:requestedFileName, highRes:false});
+    TestEngine.log("Start :" + Date());
+
+    function stopVideo()
+    {
+        try{
+            TestEngine.log("Stop :" + Date());
+            gcameras[0].stopVideoCapture();
+
+            TestEngine.log("Wait :" + Date());
+            //check if allback has been executed
+            setTimeout(checkCompletness, 10000);
+        }
+        catch(e)
+        {
+            TestEngine.log("Exception: " + e);
+        }
+    }
+
+    setTimeout(stopVideo, VideoTime);
+}
+
+function TestCameraCancel()
+{
+    var number =5;
+
+    var expectedPhotos = 4;
+
+    var done = 0;
+
+
+
+    function success(filename)
+    {
+        done = done +1;
+        TestEngine.log("filename = " + filename);
+        TestEngine.test("image captured", true)
+        checkStatus();
+    }
+
+    function error(e)
+    {
+        done = done +1;
+        checkStatus();
+    }
+
+    var obj = TestEngine.registerCallback("cancel test ", testPassed, testFail);
+
+    function checkStatus()
+    {
+        if(done > expectedPhotos)
+        {
+            obj.errorCallback();
+        }
+
+        if(done == expectedPhotos)
+        {
+            obj.successCallback();
+        }
+    }
+
+    function testFail()
+    {
+            TestEngine.test("Cancel take picture", false)
+    }
+
+    function testPassed()
+    {
+            TestEngine.test("Cancel take picture", true)
+    }
+
+
+    TestEngine.log("Take picutre");
+    for (i=1;i<number+1;i++)
+    {
+        var requestedFileName = GetFileName("images/test_photo_"+i+"_",".jpg");
+
+        var pending=gcameras[0].captureImage(success,
+                                 error,
+                                 {destinationFilename:requestedFileName, highRes:false});
+
+        if(i==4){
+            TestEngine.log("Operation will be canceled");
+            pending.cancel();
+            TestEngine.log("Operation should be canceled");
+        }
+  }
+
+
+}
+
+//******************************* new to review below *******************************
+
+function parameterCorrectnessSuccessCallback(){
+    TestEngine.logErr("SuccessCallback on invalid parameter");
+}
+
+function parameterCorrectnessErrorCallback(err){
+    TestEngine.logErr("ErrorCallback invoked on invalid parameter (error should be thrown)");
+}
+
+// Cam0014
+// Input: errorCallback = null, others = valid
+// Result: Test passes.
+function TestGetCamerasNullErrorCallback()
+{
+    function GetCamerasOnSuccess(cameras)
+    {
+        TestEngine.test("getCameras()", isArray(cameras));
+    }
+
+    var cb = TestEngine.registerCallback("getCameras", GetCamerasOnSuccess, null);
+    deviceapis.camera.getCameras(cb.successCallback, null);
+}
+
+// Cam0015
+// Input: successCallback = null, others = valid
+// Result: Test fails with error callback called with INVALID_VALUES_ERR.
+function TestGetCamerasNullSuccessCallback()
+{
+    function GetCamerasOnError(error)
+    {
+        TestEngine.test("getCameras()", (error.code == INVALID_VALUES_ERR));
+    }
+
+    var cb = TestEngine.registerCallback("getCameras", null, GetCamerasOnError);
+    deviceapis.camera.getCameras(null, cb.errorCallback);
+}
+
+// Cam0016
+// Input: successCallback = undefined, others = valid
+// Result: Test fails with TYPE_MISMATCH_ERR thrown in place.
+function TestGetCamerasUndefinedSuccessCallback()
+{
+    function GetCamerasOnError(error)
+    {
+        TestEngine.test("getCameras()", false);
+    }
+
+    TestEngine.testPresetError(
+        "getCameras()",
+        function() {
+            deviceapis.camera.getCameras(undefined, GetCamerasOnError);
+        },
+        TYPE_MISMATCH_ERR
+    );
+}
+
+// Cam0017
+// Input: successCallback = null, errorCallback = null
+// Result: Test fails silently.
+function TestGetCamerasNullCallbacks()
+{
+    testNoExceptionWithMessage("getCameras()", function() {
+        deviceapis.camera.getCameras(null, null);
+    });
+}
+
+// Cam0018
+// Input: errorCallback = not passed, others = valid
+// Result: Test passes.
+function TestGetCamerasNoErrorCallback()
+{
+    function GetCamerasOnSuccess(cameras)
+    {
+        TestEngine.test("getCameras()", isArray(cameras));
+    }
+
+    var cb = TestEngine.registerCallback("getCameras", GetCamerasOnSuccess, null);
+    deviceapis.camera.getCameras(cb.successCallback);
+}
+
+// Cam0019
+// Result: Test passes.
+function TestCameraId()
+{
+    TestEngine.test("camaras available", isArray(gcameras) && gcameras.length > 0);
+    for (var i = 0; i < gcameras.length; ++i) {
+        TestEngine.test("id", gcameras[i].id === "front" || gcameras[i].id === "rear");
+    }
+}
+
+// Cam0020
+// Input: options = null, others = valid
+// Result: Test passes.
+function TestCaptureImageNullOptions()
+{
+    function CaptureImageOnSuccess(filename)
+    {
+        TestEngine.test("captureImage()", true);
+    }
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", false)
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, CaptureImageOnError);
+    gcameras[0].captureImage(cb.successCallback, cb.errorCallback, null);
+}
+
+// Cam0021
+// Input: options = undefined, others = valid
+// Result: Test passes.
+function TestCaptureImageUndefinedOptions()
+{
+    function CaptureImageOnSuccess(filename)
+    {
+        TestEngine.test("captureImage()", true);
+    }
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", false)
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, CaptureImageOnError);
+    gcameras[0].captureImage(cb.successCallback, cb.errorCallback, undefined);
+}
+
+// Cam0022
+// Input: errorCallback = null, others = valid
+// Result: Test passes.
+function TestCaptureImageNullErrorCallback()
+{
+    var options = {
+        destinationFilename: 'images/TestCaptureImageNullErrorCallback.jpg'
+    };
+    function CaptureImageOnSuccess(filename)
+    {
+        // Don't compare paths if 'images' is passed as virtual root since Tizen
+        // points 'images' to the same location as 'videos' and returns filename
+        // with 'videos' virtual root instead of 'images'.
+        // TestEngine.test("captureImage()", (options.destinationFilename == filename));
+        TestEngine.test("captureImage()", true);
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, null);
+    gcameras[0].captureImage(cb.successCallback, null, options);
+}
+
+// Cam0023
+// Input: successCallback = null, options = omitted, others = valid
+// Result: Test fails with error callback called with INVALID_VALUES_ERR.
+function TestCaptureImageNullSuccessCallback()
+{
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", (error.code == INVALID_VALUES_ERR));
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", null, CaptureImageOnError);
+    gcameras[0].captureImage(null, cb.errorCallback);
+}
+
+// Cam0024
+// Input: successCallback = undefined, options = omitted, others = valid
+// Result: Test fails with TYPE_MISMATCH_ERR thrown in place.
+function TestCaptureImageUndefinedSuccessCallback()
+{
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", false);
+    }
+
+    TestEngine.testPresetError(
+        "captureImage()",
+        function() {
+            gcameras[0].captureImage(undefined, CaptureImageOnError);
+        },
+        TYPE_MISMATCH_ERR
+    );
+}
+
+// Cam0025
+// Input: successCallback = null, errorCallback = null, options = omitted
+// Result: Test fails silently.
+function TestCaptureImageNullCallbacks()
+{
+    testNoExceptionWithMessage("captureImage()", function() {
+        gcameras[0].captureImage(null, null);
+    });
+}
+
+// Cam0026
+// Input: errorCallback = omitted, options = omitted, others = valid
+// Result: Test passes.
+function TestCaptureImageNoErrorCallback()
+{
+    function CaptureImageOnSuccess(filename)
+    {
+        TestEngine.test("captureImage()", true);
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, null);
+    gcameras[0].captureImage(cb.successCallback);
+}
+
+// Cam0027
+// Input: options = invalid filename, others = valid
+// Result: Test passes.
+function TestCaptureImageInvalidFilename()
+{
+    var options = {
+        destinationFilename: {}
+    };
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", false);
+    }
+    function CaptureImageOnSuccess(filename)
+    {
+        TestEngine.test("captureImage()", true);
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, CaptureImageOnError);
+    gcameras[0].captureImage(cb.successCallback, cb.errorCallback, options);
+}
+
+// Cam0028
+// Input: options = invalid highRes, others = valid
+// Result: Test passes.
+function TestCaptureImageInvalidHighRes()
+{
+    var options = {
+        highRes: {}
+    };
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", false);
+    }
+    function CaptureImageOnSuccess(filename)
+    {
+        TestEngine.test("captureImage()", true);
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, CaptureImageOnError);
+    gcameras[0].captureImage(cb.successCallback, cb.errorCallback, options);
+}
+
+// Cam0029
+// Input: options = null, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureNullOptions()
+{
+    function Step1()
+    {
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            TestEngine.test("startVideoCapture()", true);
+        }
+        function StartVideoCaptureOnError(error)
+        {
+            TestEngine.test("startVideoCapture()", false)
+        }
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, StartVideoCaptureOnError);
+        gcameras[0].startVideoCapture(cb.successCallback, cb.errorCallback, null);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0030
+// Input: options = undefined, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureUndefinedOptions()
+{
+    function Step1()
+    {
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            TestEngine.test("startVideoCapture()", true);
+        }
+        function StartVideoCaptureOnError(error)
+        {
+            TestEngine.test("startVideoCapture()", false)
+        }
+
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, StartVideoCaptureOnError);
+        gcameras[0].startVideoCapture(cb.successCallback, cb.errorCallback, undefined);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0031
+// Input: errorCallback = null, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureNullErrorCallback()
+{
+    function Step1()
+    {
+        var options = {
+            destinationFilename: 'images/TestStartVideoCaptureNullErrorCallback.3gp'
+        };
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            // Don't compare paths if 'images' is passed as virtual root since Tizen
+            // points 'images' to the same location as 'videos' and returns filename
+            // with 'videos' virtual root instead of 'images'.
+            // TestEngine.test("StartVideoCapture()", (options.destinationFilename == filename));
+            TestEngine.test("startVideoCapture()", true);
+        }
+
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, null);
+        gcameras[0].startVideoCapture(cb.successCallback, null, options);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0032
+// Input: successCallback = null, options = omitted, others = valid
+// Result: Test fails with error callback called with INVALID_VALUES_ERR.
+function TestStartVideoCaptureNullSuccessCallback()
+{
+    function StartVideoCaptureOnError(error)
+    {
+        TestEngine.test("startVideoCapture()", (error.code == INVALID_VALUES_ERR));
+    }
+
+    var cb = TestEngine.registerCallback("startVideoCapture", null, StartVideoCaptureOnError);
+    gcameras[0].startVideoCapture(null, cb.errorCallback);
+}
+
+// Cam0033
+// Input: successCallback = undefined, options = omitted, others = valid
+// Result: Test fails with TYPE_MISMATCH_ERR thrown in place.
+function TestStartVideoCaptureUndefinedSuccessCallback()
+{
+    function StartVideoCaptureOnError(error)
+    {
+        TestEngine.test("startVideoCapture()", false);
+    }
+
+    TestEngine.testPresetError(
+        "startVideoCapture()",
+        function() {
+            gcameras[0].startVideoCapture(undefined, StartVideoCaptureOnError);
+        },
+        TYPE_MISMATCH_ERR
+    );
+}
+
+// Cam0034
+// Input: successCallback = null, errorCallback = null, options = omitted
+// Result: Test fails silently.
+function TestStartVideoCaptureNullCallbacks()
+{
+    testNoExceptionWithMessage("startVideoCapture()", function() {
+        gcameras[0].startVideoCapture(null, null);
+    });
+}
+
+// Cam0035
+// Input: errorCallback = omitted, options = omitted, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureNoErrorCallback()
+{
+    function Step1()
+    {
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            TestEngine.test("startVideoCapture()", true);
+        }
+
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, null);
+        gcameras[0].startVideoCapture(cb.successCallback);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0036
+// Input: options = invalid filename, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureInvalidFilename()
+{
+    function Step1()
+    {
+        var options = {
+            destinationFilename: {}
+        };
+        function StartVideoCaptureOnError(error)
+        {
+            TestEngine.test("startVideoCapture()", false);
+        }
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            TestEngine.test("startVideoCapture()", true);
+        }
+
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, StartVideoCaptureOnError);
+        gcameras[0].startVideoCapture(cb.successCallback, cb.errorCallback, options);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0037
+// Input: options = invalid highRes, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureInvalidHighRes()
+{
+    function Step1()
+    {
+        var options = {
+            highRes: {}
+        };
+        function StartVideoCaptureOnError(error)
+        {
+            TestEngine.test("startVideoCapture()", false);
+        }
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            TestEngine.test("startVideoCapture()", true);
+        }
+
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, StartVideoCaptureOnError);
+        gcameras[0].startVideoCapture(cb.successCallback, cb.errorCallback, options);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0038
+// Input: errorCallback = null, others = valid
+// Result: Test passes.
+function TestCreatePreviewNodeNullErrorCallback()
+{
+    function CreatePreviewNodeOnSuccess(domObj)
+    {
+        TestEngine.test("createPreviewNode()", true);
+    }
+
+    var cb = TestEngine.registerCallback("createPreviewNode", CreatePreviewNodeOnSuccess, null);
+    gcameras[0].createPreviewNode(cb.successCallback, null);
+}
+
+// Cam0039
+// Input: successCallback = null, others = valid
+// Result: Test fails with error callback called with INVALID_VALUES_ERR.
+function TestCreatePreviewNodeNullSuccessCallback()
+{
+    function CreatePreviewNodeOnError(error)
+    {
+        TestEngine.test("createPreviewNode()", (error.code == INVALID_VALUES_ERR));
+    }
+
+    var cb = TestEngine.registerCallback("createPreviewNode", null, CreatePreviewNodeOnError);
+    gcameras[0].createPreviewNode(null, cb.errorCallback);
+}
+
+// Cam0040
+// Input: successCallback = undefined, others = valid
+// Result: Test fails with TYPE_MISMATCH_ERR thrown in place.
+function TestCreatePreviewNodeUndefinedSuccessCallback()
+{
+    function CreatePreviewNodeOnError(error)
+    {
+        TestEngine.test("createPreviewNode()", false);
+    }
+
+    TestEngine.testPresetError(
+        "createPreviewNode()",
+        function() {
+            gcameras[0].createPreviewNode(undefined, CreatePreviewNodeOnError);
+        },
+        TYPE_MISMATCH_ERR
+    );
+}
+
+// Cam0041
+// Input: successCallback = null, errorCallback = null
+// Result: Test fails silently.
+function TestCreatePreviewNodeNullCallbacks()
+{
+    testNoExceptionWithMessage("createPreviewNode()", function() {
+        gcameras[0].createPreviewNode(null, null);
+    });
+}
+
+// Cam0042
+// Input: errorCallback = not passed, others = valid
+// Result: Test passes.
+function TestCreatePreviewNodeNoErrorCallback()
+{
+    function CreatePreviewNodeOnSuccess(domObj)
+    {
+        TestEngine.test("createPreviewNode()", true);
+    }
+
+    var cb = TestEngine.registerCallback("createPreviewNode", CreatePreviewNodeOnSuccess, null);
+    gcameras[0].createPreviewNode(cb.successCallback);
+}
+
+//=============================================================================
+//TestJavaScript();
+
+function SimpleVideoTest()
+{
+    TestEngine.log ("START")
+
+    function Succ(cameras){
+        gcameras = cameras;
+        Record();
+    }
+
+    function Errr(err){
+        TestEngine.logErr("Get cameras failed. Exception code: " + err.code);
+    }
+
+    deviceapis.camera.getCameras(Succ, Errr);
+}
+
+function Record()
+{
+
+    function success(filename)
+    {
+        TestEngine.log("video capture success");
+        callbackExecuted = true;
+    }
+
+    function errorCb(e)
+    {
+        TestEngine.log("video captured errro");
+        callbackExecuted = true;
+    }
+
+    var requestedFileName = GetFileName("videos/test_video_",".mp4");
+    TestEngine.log("Start 1:" + Date());
+    gcameras[0].startVideoCapture(success,
+                                  errorCb,
+                                  {destinationFilename:requestedFileName, highRes:false});
+    TestEngine.log("Start 2:" + Date());
+
+//    waitMs(7000);
+//    gcameras[0].stopVideoCapture();
+//    TestEngine.log("Stop :" + Date());
+
+    function stopVideo()
+    {
+        try{
+            TestEngine.log("Stop :" + Date());
+            gcameras[0].stopVideoCapture();
+
+            TestEngine.log("Wait :" + Date());
+            //time for invoke callback
+            waitMs(3000);
+            TestEngine.log("After Wait :" + Date());
+
+            if(!callbackExecuted)
+            {
+                TestEngine.test("Video capture time out", false);
+            }
+        }
+        catch(e)
+        {
+            TestEngine.log("Exception: " + e);
+        }
+    }
+    TestEngine.log("Before timeout")
+    setTimeout(stopVideo, VideoTime);
+}
+
+function onCameraError(err)
+{
+    TestEngine.test("Camera error: " + err.code, false);
+}
+
+function TestGetImageOK()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image1.jpg",
+        function(fileName) {
+            TestEngine.test("Take picture image1.jpg : " + fileName,
+                            fileName === "images/image1.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image1.jpg",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+function TestGetImageOK2()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image2.jpeg",
+        function(fileName) {
+            TestEngine.test("Take picture image2.jpeg : " + fileName,
+                            fileName === "images/image2.jpeg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image2.jpeg",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+
+function TestGetImagePnG()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image3.PnG",
+        function(fileName) {
+            TestEngine.test("Take picture image3.PnG : " + fileName,
+                            fileName === "images/image3.PnG" || fileName === "images/image3.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image3.PnG",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+
+function TestGetImageNoExt()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image4",
+        function(fileName) {
+            TestEngine.test("Take picture image4 : " + fileName,
+                            fileName === "images/image4.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image4",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+function TestGetImageTiff()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image1.tiff",
+        function(fileName) {
+            TestEngine.test("Take picture image1.tiff : " + fileName,
+                            fileName === "images/image1.tiff" || fileName === "images/image1.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image1.tiff",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+function TestGetImageBMP()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image2.BMP",
+        function(fileName) {
+            TestEngine.test("Take picture image2.BMP : " + fileName,
+                            fileName === "images/image2.BMP" || fileName === "images/image2.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image2.BMP",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+function TestGetImageWrong()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image3.wrong",
+        function(fileName) {
+            TestEngine.test("Take picture image3.wrong : " + fileName,
+                            fileName === "images/image3.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image3.wrong",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+function TestGetImageXbm()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image4.xbm",
+        function(fileName) {
+            TestEngine.test("Take picture image4.xbm : " + fileName,
+                            fileName === "images/image4.xbm" || fileName === "images/image4.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image4.xbm",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+
+//SimpleVideoTest();
+TestEngine.setTestSuiteName("Camera", 60000); // test suite timeout 60sec.
+
+TestEngine.addTest(true, TestGetCameras, "[Camera] Get cameras");
+//TestEngine.addTest(false, TestCaseCameraArrayProperties, "[Camera] Camera array properties");
+//TestEngine.addTest(false, TestJavaScript, "[Camera] JavaScript");
+//
+//TestEngine.addTest(false, TestCameraFunctionality_PreviewStart, "[Camera] Camrea preview start");
+//TestEngine.addTest(false, TestCameraFunctionality_TakePicture, "[Camera] Camrea picture");
+//TestEngine.addTest(false, TestCameraFunctionality_Video, "[Camera] Camrea video");
+//TestEngine.addTest(false, TestCameraFunctionality_PreviewStop, "[Camera] Camrea preview stop");
+//TestEngine.addTest(false, TestCameraCancel, "[Camera] Cancel take picture");
+//
+//TestEngine.addTest(false,TestGetCamerasNullErrorCallback, "Cam0014");
+//TestEngine.addTest(false,TestGetCamerasNullSuccessCallback, "Cam0015");
+//TestEngine.addTest(false,TestGetCamerasUndefinedSuccessCallback, "Cam0016");
+//TestEngine.addTest(false,TestGetCamerasNullCallbacks, "Cam0017");
+//TestEngine.addTest(false,TestGetCamerasNoErrorCallback, "Cam0018");
+//TestEngine.addTest(false,TestCameraId, "Cam0019");
+//TestEngine.addTest(false,TestCaptureImageNullOptions, "Cam0020");
+//TestEngine.addTest(false,TestCaptureImageUndefinedOptions, "Cam0021");
+//TestEngine.addTest(false,TestCaptureImageNullErrorCallback, "Cam0022");
+//TestEngine.addTest(false,TestCaptureImageNullSuccessCallback, "Cam0023");
+//TestEngine.addTest(false,TestCaptureImageUndefinedSuccessCallback, "Cam0024");
+//TestEngine.addTest(false,TestCaptureImageNullCallbacks, "Cam0025");
+//TestEngine.addTest(false,TestCaptureImageNoErrorCallback, "Cam0026");
+//TestEngine.addTest(false,TestCaptureImageInvalidFilename, "Cam0027");
+//TestEngine.addTest(false,TestCaptureImageInvalidHighRes, "Cam0028");
+//TestEngine.addTest(false,TestStartVideoCaptureNullOptions, "Cam0029");
+//TestEngine.addTest(false,TestStartVideoCaptureUndefinedOptions, "Cam0030");
+//TestEngine.addTest(false,TestStartVideoCaptureNullErrorCallback, "Cam0031");
+//TestEngine.addTest(false,TestStartVideoCaptureNullSuccessCallback, "Cam0032");
+//TestEngine.addTest(false,TestStartVideoCaptureUndefinedSuccessCallback, "Cam0033");
+//TestEngine.addTest(false,TestStartVideoCaptureNullCallbacks, "Cam0034");
+//TestEngine.addTest(false,TestStartVideoCaptureNoErrorCallback, "Cam0035");
+//TestEngine.addTest(false,TestStartVideoCaptureInvalidFilename, "Cam0036");
+//TestEngine.addTest(false,TestStartVideoCaptureInvalidHighRes, "Cam0037");
+//TestEngine.addTest(false,TestCreatePreviewNodeNullErrorCallback, "Cam0038");
+//TestEngine.addTest(false,TestCreatePreviewNodeNullSuccessCallback, "Cam0039");
+//TestEngine.addTest(false,TestCreatePreviewNodeUndefinedSuccessCallback, "Cam0040");
+//TestEngine.addTest(false,TestCreatePreviewNodeNullCallbacks, "Cam0041");
+//TestEngine.addTest(false,TestCreatePreviewNodeNoErrorCallback, "Cam0042");
+//
+//TestEngine.addTest(true, TestGetImageOK, "[CameraFileFormat] get image : image1.jpg");
+//TestEngine.addTest(true, TestGetImageOK2, "[CameraFileFormat] get image : image2.jpeg");
+//TestEngine.addTest(true, TestGetImagePnG, "[CameraFileFormat] get image : image3.PnG");
+//TestEngine.addTest(true, TestGetImageNoExt, "[CameraFileFormat] get image : image4");
+//TestEngine.addTest(true, TestGetImageTiff, "[CameraFileFormat] get image : image1.tiff");
+//TestEngine.addTest(true, TestGetImageBMP, "[CameraFileFormat] get image : image2.MBP");
+//TestEngine.addTest(true, TestGetImageWrong, "[CameraFileFormat] get image : image3.wrong");
+//TestEngine.addTest(true, TestGetImageXbm, "[CameraFileFormat] get image : image4.xbm");
+//=============================================================================
+
+function testNoExceptionWithMessage(message, fun) {
+  var testResult = true;
+  try {
+    fun();
+  }
+  catch (e) {
+    testResult = false;
+  }
+  TestEngine.test(message, testResult);
+}
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestContact.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestContact.js
new file mode 100644 (file)
index 0000000..264c4b5
--- /dev/null
@@ -0,0 +1,565 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function test_Contact_Presence() {
+    TestEngine.testPresence("Checking contact presence", deviceapis.pim.contact);
+}
+
+function test_Create_Contact_001() {
+    function AddressBooksCB001(addressbooks)
+    {
+        TestEngine.test("get AddressBooks - success", true);
+//        if(addressbooks.length > 0)
+//        {
+//            var addressbook = addressbooks[0];
+//            try{
+//                var contact = addressbook.createContact(
+//                                                        {
+//                                                        firstName:'Brad',
+//                                                        lastName:'Pitt'
+//                                                        });
+//
+//                TestEngine.test("check firstName", contact.firstName =="Brad");
+//                TestEngine.test("check lastName", contact.lastName =="Pitt");
+//            }
+//            catch(error)
+//            {
+//                TestEngine.logErr("createContact,error.code="+error.code);
+//            }
+//        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB001,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_002() {
+    function AddressBooksCB002(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        addresses:[{types:['WORK'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Lushanlu, 1", postalCode:"210012", additionalInformation:"addinfo1"},
+                                                                        {types:['HOME'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Sanshanjie, 99", postalCode:"210009", additionalInformation:"addinfo2"}]
+                                                        });
+                TestEngine.test("check addresses length", contact.addresses.length == 2);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact, error="+error);
+            }
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB002,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_003() {
+    function AddressBooksCB003(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        phoneNumbers:[{number:'111111',types:['WORK']},
+                                                                    {number:'222222',types:['HOME']},
+                                                                    {number:'333333',types:['CAR']},
+                                                                    {number:'444444',types:['CELL']},
+                                                                    {number:'555555',types:['FAX']},
+                                                                    {number:'666666',types:['PAGER']},
+                                                                    {number:'7777777',types:['PREF']}]
+                                                                    });
+                TestEngine.test("check phoneNumbers length", contact.phoneNumbers.length == 7);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB003,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_004() {
+    function AddressBooksCB004(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        emails:[{email:"work@domain.com",types:['WORK']},
+                                                                {email:"home@domain.com",types:['HOME']},
+                                                                {email:"pref@domain.com",types:['PREF']}]
+                                                        });
+                TestEngine.test("check emails length", contact.emails.length == 3);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB004,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_005() {
+    function AddressBooksCB005(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        nicknames:['nickname1','nickname2','nickname3','nickname4']
+                                                        });
+                TestEngine.test("check nicknames length", contact.nicknames.length == 4);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB005,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_006() {
+    function AddressBooksCB006(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        photoURI:'/opt/apps/widget/tests/attachments/attach1.jpg'
+                                                        });
+                TestEngine.test("check photoURI", contact.photoURI == "/opt/apps/widget/tests/attachments/attach1.jpg");
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB006,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_007() {
+    function AddressBooksCB007(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        firstName:'Brad',
+                                                        lastName:'Pitt',
+                                                        addresses:[{types:['WORK'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Lushanlu, 1", postalCode:"210012", additionalInformation:"addinfo1"},
+                                                                        {types:['HOME'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Sanshanjie, 99", postalCode:"210009", additionalInformation:"addinfo2"}],
+                                                        phoneNumbers:[{number:'111111',types:['WORK']},
+                                                                    {number:'222222',types:['HOME']},
+                                                                    {number:'333333',types:['CAR']},
+                                                                    {number:'444444',types:['CELL']},
+                                                                    {number:'555555',types:['FAX']},
+                                                                    {number:'666666',types:['PAGER']},
+                                                                    {number:'7777777',types:['PREF']}],
+                                                        emails:[{email:"work@domain.com",types:['WORK']},
+                                                                {email:"home@domain.com",types:['HOME']},
+                                                                {email:"pref@domain.com",types:['PREF']}],
+                                                        nicknames:['nickname1','nickname2','nickname3','nickname4']
+                                                        });
+                TestEngine.test("check firstName", contact.firstName =="Brad");
+                TestEngine.test("check lastName", contact.lastName =="Pitt");
+                TestEngine.test("check addresses length", contact.addresses.length == 2);
+                TestEngine.test("check phoneNumbers length", contact.phoneNumbers.length == 7);
+                TestEngine.test("check emails length", contact.emails.length == 3);
+                TestEngine.test("check nicknames length", contact.nicknames.length == 4);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB007,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Get_AddressBooks_001() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.logOK("getAddressBooksCB");
+        TestEngine.log("addressbooks length = " + addressbooks.length);
+
+        for(var i=0;i<addressbooks.length;i++)
+        {
+            TestEngine.log(addressbooks[i].name);
+            TestEngine.log(addressbooks[i].type);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Add_Contact_006() {
+    function AddressBooksCB013(addressbooks)
+    {
+        var contact;
+        TestEngine.log("AddressBooksCB");
+
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            TestEngine.log("The addressbook type is " + addressbook.type +  " and name " + addressbook.name);
+
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        firstName:'Brad',
+                                                        lastName:'Pitt',
+                                                        addresses:[{types:['PREF'],country:"Finland",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Sanshanjie, 99", postalCode:"210009", additionalInformation:"Other"},
+                                                                        {types:['HOME'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Sanshanjie, 99", postalCode:"210009", additionalInformation:"Home"},
+                                                                        {types:['WORK'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Lushanlu, 1", postalCode:"210012", additionalInformation:"Work"}],
+                                                        phoneNumbers:[{number:'111111',types:['WORK']},
+                                                                    {number:'222222',types:['HOME']},
+                                                                    {number:'333333',types:['CAR']},
+                                                                    {number:'444444',types:['CELL']},
+                                                                    {number:'555555',types:['FAX']},
+                                                                    {number:'666666',types:['PAGER']},
+                                                                    {number:'7777777',types:['PREF']}],
+                                                        emails:[{email:"work@domain.com",types:['WORK']},
+                                                                {email:"home@domain.com",types:['HOME']},
+                                                                {email:"pref@domain.com",types:['PREF']}],
+                                                        nicknames:['nickname1','nickname2','nickname3','nickname4'],
+                                                        photoURI:'/opt/apps/widget/tests/attachments/attach1.jpg'
+                                                        });
+                var callback=TestEngine.registerCallback("addContact",contactAddedCB,addContactErrorCallback);
+                addressbook.addContact(callback.successCallback, callback.errorCallback, contact);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+        }
+    }
+    deviceapis.pim.contact.getAddressBooks(AddressBooksCB013,  getAddressBooksErrorCallback);
+}
+
+
+function test_findContacts_001() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback);
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_findContacts_002() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback,{firstName:'%ra%'});
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_findContacts_003() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback,{lastName:'%itt%'});
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_findContacts_004() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback,{phoneNumbers:[{number:'111111',types:['WORK']}]});
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_findContacts_005() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback,{addresses:[{types:['WORK'],country:"China"}]});
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_findContacts_006() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback,{emails:[{email:"work@domain.com%",types:['WORK']}]});
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_deleteContacts_001() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        function findContactSuccessCallback(contacts)
+        {
+            TestEngine.log("findContactSuccessCallback");
+            TestEngine.test("Contact list not empty", contacts.length > 0);
+            function contactDeleteSuccessCallback()
+            {
+                TestEngine.logOK("contactDeleteSuccessCallback Callback");
+            }
+
+            var callback3=TestEngine.registerCallback("deleteContacts",contactDeleteSuccessCallback,deleteContactErrorCallback);
+            addressbooks[0].deleteContact(callback3.successCallback, callback3.errorCallback, contacts[0].id);
+        }
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",findContactSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback);
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_updateContacts_001() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        function findContactSuccessCallback(contacts)
+        {
+            TestEngine.log("findContactSuccessCallback");
+            function contactUpdateSuccessCallback()
+            {
+                TestEngine.logOK("contactUpdateSuccessCallback Callback");
+            }
+            TestEngine.test("Contact list not empty", contacts.length > 0);
+            TestEngine.log("contacts[0] id ="+contacts[0].id );
+            contacts[0].firstName = "Asuka3";
+            contacts[0].lastName = "Langley3";
+            contacts[0].photoURI= "/opt/apps/widget/tests/attachments/attach1.jpg";
+            var phoneNumber ={number:'999999',types:['WORK']};
+            var address = {types:['HOME'],country:"Test",region:"Test",city:"Test",county:"Test",streetAddress:"Test", postalCode:"Test", additionalInformation:"Test"};
+            var email={email:"test@domain.com",types:['WORK']};
+
+            TestEngine.log("photoURI =" + contacts[0].photoURI);
+            if(contacts[0].phoneNumbers.length>0)
+            {
+                contacts[0].phoneNumbers[0]=phoneNumber;
+            }
+
+            if(contacts[0].addresses.length>0)
+            {
+                contacts[0].addresses[0]=address;
+            }
+
+            if(contacts[0].emails.length>0)
+            {
+                contacts[0].emails[0]=email;
+            }
+
+            var callback3=TestEngine.registerCallback("updateContact",contactUpdateSuccessCallback,updateContactErrorCallback);
+            addressbooks[0].updateContact(callback3.successCallback, callback3.errorCallback, contacts[0]);
+        }
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",findContactSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback);
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function contactAddedCB(contact)
+{
+    TestEngine.log("typeof(contact) =" + typeof(contact));
+    TestEngine.testPresence("Checking contact presence", contact);
+    TestEngine.test("check firstName", contact.firstName =="Brad");
+    TestEngine.test("check lastName", contact.lastName =="Pitt");
+    TestEngine.test("check addresses length", contact.addresses.length == 3);
+    TestEngine.test("check phoneNumbers length", contact.phoneNumbers.length == 7);
+    TestEngine.test("check emails length", contact.emails.length == 3);
+    //TestEngine.test("check nicknames length", contact.nicknames.length == 4);
+    TestEngine.test("check photoURI", contact.photoURI == "/opt/apps/widget/tests/attachments/attach1.jpg");
+    TestEngine.logOK("contactAddedCB Callback");
+}
+
+function contactSearchSuccessCallback(contacts)
+{
+    TestEngine.log(""+contacts.length + " results found.");
+    for(var i=0;i<contacts.length;i++)
+    {
+        TestEngine.log("contacts["+i+"] id=" + contacts[i].id);
+        TestEngine.log("contacts["+i+"] firstName=" + contacts[i].firstName);
+        TestEngine.log("contacts["+i+"] lastName=" + contacts[i].lastName);
+        TestEngine.log("contacts["+i+"] addresses length=" + contacts[i].addresses.length);
+        TestEngine.log("contacts["+i+"] phoneNumbers length=" + contacts[i].phoneNumbers.length);
+        TestEngine.log("contacts["+i+"] emails length =" + contacts[i].emails.length );
+        TestEngine.log("contacts["+i+"] nicknames length=" + contacts[i].nicknames.length);
+    }
+    TestEngine.logOK("contactAddedCB Callback");
+
+}
+
+function getAddressBooksErrorCallback(response)
+{
+    TestEngine.logErr("getAddressBooks Error Callback");
+}
+
+function addContactErrorCallback(response)
+{
+    TestEngine.logErr("contactAddedCB Callback");
+}
+
+function findContactErrorCallback(response)
+{
+    TestEngine.logErr("find contact error Callback");
+}
+
+function deleteContactErrorCallback(response)
+{
+    TestEngine.logErr("Delete contact error Callback");
+}
+
+function updateContactErrorCallback(response)
+{
+    TestEngine.logErr("Update contact error Callback");
+}
+
+TestEngine.setTestSuiteName('[WAC2.0][Contact]',60*1000);
+//TestEngine.addTest(true,test_Contact_Presence,"[WAC2.0][Contact]test_Contact");
+TestEngine.addTest(true,test_Create_Contact_001,"[WAC2.0][Contact]test_Create_Contact_001");
+//TestEngine.addTest(true,test_Create_Contact_002,"[WAC2.0][Contact]test_Create_Contact_002");
+//TestEngine.addTest(true,test_Create_Contact_003,"[WAC2.0][Contact]test_Create_Contact_003");
+//TestEngine.addTest(true,test_Create_Contact_004,"[WAC2.0][Contact]test_Create_Contact_004");
+//TestEngine.addTest(true,test_Create_Contact_005,"[WAC2.0][Contact]test_Create_Contact_005");
+//TestEngine.addTest(true,test_Create_Contact_006,"[WAC2.0][Contact]test_Create_Contact_006");
+//TestEngine.addTest(true,test_Create_Contact_007,"[WAC2.0][Contact]test_Create_Contact_007");
+//
+//TestEngine.addTest(true,test_Add_Contact_006,"[WAC2.0][Contact]test_Add_Contact_006");
+//TestEngine.addTest(true,test_Get_AddressBooks_001,"[WAC2.0][Contact]test_Get_AddressBooks_001");
+//TestEngine.addTest(true,test_findContacts_001,"[WAC2.0][Contact]test_Find_findContacts_001");
+//TestEngine.addTest(true,test_findContacts_002,"[WAC2.0][Contact]test_Find_findContacts_002");
+//TestEngine.addTest(true,test_findContacts_003,"[WAC2.0][Contact]test_Find_findContacts_003");
+//TestEngine.addTest(true,test_findContacts_004,"[WAC2.0][Contact]test_Find_findContacts_004");
+//TestEngine.addTest(true,test_findContacts_005,"[WAC2.0][Contact]test_Find_findContacts_005");
+//TestEngine.addTest(true,test_findContacts_006,"[WAC2.0][Contact]test_Find_findContacts_006");
+//TestEngine.addTest(true,test_updateContacts_001,"[WAC2.0][Contact]test_Find_updateContacts_001");
+//TestEngine.addTest(true,test_deleteContacts_001,"[WAC2.0][Contact]test_Find_deleteContacts_001");
+
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestDeviceInteraction.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestDeviceInteraction.js
new file mode 100644 (file)
index 0000000..1c329cd
--- /dev/null
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of deviceinteraction plugin tests.
+ *
+ * @author      Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version     0.1
+ */
+
+var di = deviceapis.deviceinteraction;
+var filename = "wgt-package/icon.png"
+var filename2 = "wgt-package/attachments/attach1.jpg"
+var badFilename1 = "config.xml"
+var badFilename2 = ""
+var badFilename3 = "/opt/media/Sounds and music/Music/Because of you.mp3"
+
+// callbacks
+
+function expectedSuccess()
+{
+    TestEngine.test("expectedSuccess callback",true);
+    di.stopNotify();
+    di.stopVibrate();
+};
+
+function expectedFailure()
+{
+    TestEngine.test("expectedFailure callback",true);
+};
+
+function unexpectedSuccess()
+{
+    TestEngine.test("unexpectedSuccess callback",false);
+};
+
+function unexpectedFailure()
+{
+    TestEngine.test("unexpectedFailure callback",false);
+};
+
+// tests
+
+function test_deviceinteraction_presence_001()
+{
+    TestEngine.testPresence("Checking deviceapis presence", deviceapis);
+    TestEngine.testPresence2(deviceapis, 'deviceinteraction');
+}
+
+function test_deviceinteraction_functions_002()
+{
+    var props = new Array();
+    props.push(new Array('startNotify', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('stopNotify', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('startVibrate', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('stopVibrate', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('lightOn', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('lightOff', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('setWallpaper', null, null, false, TestEngine.FUNCTION));
+    TestEngine.testProperties(di, props);
+}
+
+function test_deviceinteraction_startNotify_003()
+{
+    check_ulong("startNotify");
+    di.stopNotify();
+
+    try
+    {
+        var cbObj = TestEngine.registerCallback("test", expectedSuccess, unexpectedFailure);
+        di.startNotify(cbObj.successCallback, cbObj.errorCallback, 2000);
+        TestEngine.test("No error thrown from startNotify", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_stopNotify_004()
+{
+    try
+    {
+        di.stopNotify();
+        TestEngine.test("No error thrown from stopNotify", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_startVibrate_005()
+{
+    check_ulong("startVibrate");
+    di.stopVibrate();
+
+    try
+    {
+        var cbObj = TestEngine.registerCallback("test", expectedSuccess, unexpectedFailure);
+        di.startVibrate(cbObj.successCallback, cbObj.errorCallback, 2000);
+        TestEngine.test("No error thrown from startVibrate", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_stopVibrate_006()
+{
+    try
+    {
+        di.stopVibrate();
+        TestEngine.test("No error thrown from stopVibrate", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_lightOn_008()
+{
+    check_ulong("lightOn", 2000);
+    di.lightOff();
+    try
+    {
+        var cbObj = TestEngine.registerCallback("test", expectedSuccess, unexpectedFailure);
+        di.lightOn(cbObj.successCallback, cbObj.errorCallback, 2000);
+        TestEngine.test("No error thrown from lightOn", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_lightOff_009()
+{
+    try
+    {
+        di.lightOff();
+        TestEngine.test("No error thrown from lightOff", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_setWallpaper_010()
+{
+    TestEngine.log("Checking function: deviceinteaction.setWallpaper(cb, cb, string)");
+
+    var cbObj1 = TestEngine.registerCallback("setWallpaper", expectedSuccess, unexpectedFailure);
+    di.setWallpaper(cbObj1.successCallback, cbObj1.errorCallback, filename);
+
+    var cbObj2 = TestEngine.registerCallback("setWallpaper", unexpectedSuccess, expectedFailure);
+    di.setWallpaper(undefined, cbObj2.errorCallback, filename);
+
+    TestEngine.catchErrorType("code", 17, di, "setWallpaper", 1234, unexpectedFailure, filename);
+
+    var cbObj3 = TestEngine.registerCallback("setWallpaper", expectedSuccess, unexpectedFailure);
+    di.setWallpaper(cbObj3.successCallback, undefined, filename);
+
+    TestEngine.catchErrorType("code", 17, di, "setWallpaper", unexpectedSuccess, 1234, filename);
+
+    var cbObj4 = TestEngine.registerCallback("setWallpaper", unexpectedSuccess, expectedFailure);
+    di.setWallpaper(cbObj4.successCallback, cbObj4.errorCallback, undefined);
+
+    var cbObj5 = TestEngine.registerCallback("setWallpaper", unexpectedSuccess, expectedFailure);
+    di.setWallpaper(cbObj5.successCallback, cbObj5.errorCallback, 1234);
+
+    var cbObj6 = TestEngine.registerCallback("setWallpaper", unexpectedSuccess, expectedFailure);
+    di.setWallpaper(null, cbObj6.errorCallback, filename);
+
+    var cbObj7 = TestEngine.registerCallback("setWallpaper", expectedSuccess, unexpectedFailure);
+    di.setWallpaper(cbObj7.successCallback, null, filename2);
+
+    var cbObj8 = TestEngine.registerCallback("setWallpaper", unexpectedSuccess, expectedFailure);
+    di.setWallpaper(cbObj8.successCallback, cbObj8.errorCallback, null);
+}
+
+function check_ulong(func)
+{
+    TestEngine.log("Checking function: deviceinteaction." + func + "(unsigned long)");
+
+    TestEngine.catchErrorType("code", 17, di, func, expectedSuccess, unexpectedFailure);
+
+    var cbObj1 = TestEngine.registerCallback("null param", expectedSuccess, unexpectedFailure);
+    di[func](cbObj1.successCallback, cbObj1.errorCallback, null);
+
+    var cbObj2 = TestEngine.registerCallback("undefined param", expectedSuccess, unexpectedFailure);
+    di[func](cbObj2.successCallback, cbObj2.errorCallback, undefined);
+
+    var cbObj3 = TestEngine.registerCallback("undefined param", unexpectedSuccess, expectedFailure);
+    di[func](cbObj3.successCallback, cbObj3.errorCallback, -666);
+
+    var cbObj4 = TestEngine.registerCallback("undefined param", expectedSuccess, unexpectedFailure);
+    di[func](cbObj4.successCallback, cbObj4.errorCallback, "test");
+
+    var cbObj5 = TestEngine.registerCallback("undefined param", expectedSuccess, unexpectedFailure);
+    di[func](cbObj5.successCallback, cbObj5.errorCallback, new Date());
+
+    var cbObj6 = TestEngine.registerCallback("undefined param", expectedSuccess, unexpectedFailure);
+    di[func](cbObj6.successCallback, cbObj6.errorCallback, [6, 6, 6]);
+}
+
+//=============================================================================
+TestEngine.setTestSuiteName('[WAC2.0][DeviceInteractionManager]', 10*1000);
+//TestEngine.addTest(true,test_deviceinteraction_presence_001, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_presence_001");
+//TestEngine.addTest(true,test_deviceinteraction_functions_002, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_functions_002");
+//TestEngine.addTest(true,test_deviceinteraction_startNotify_003, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_startNotify_003");
+//TestEngine.addTest(true,test_deviceinteraction_stopNotify_004, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_stopNotify_004");
+//TestEngine.addTest(true,test_deviceinteraction_startVibrate_005, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_startVibrate_005");
+TestEngine.addTest(true,test_deviceinteraction_stopVibrate_006, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_stopVibrate_006");
+//TestEngine.addTest(true,test_deviceinteraction_lightOn_008, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_lightOn_008");
+//TestEngine.addTest(true,test_deviceinteraction_lightOff_009, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_lightOff_009");
+//TestEngine.addTest(true,test_deviceinteraction_setWallpaper_010, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_setWallpaper_010");
+//=============================================================================
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestDevicestatus.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestDevicestatus.js
new file mode 100644 (file)
index 0000000..ab8538b
--- /dev/null
@@ -0,0 +1,1148 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test contact class.
+ *
+ * @author      Pawel Misiak (p.misiak@samsung.com)
+ * @author      Shi Hezhang (hezhang.shi@samsung.com)
+ * @version     0.1
+ */
+
+var DevStatusObj = deviceapis.devicestatus;
+
+var aspectsProperty=Object();
+aspectsProperty['Battery']=['batteryLevel', 'batteryBeingCharged'];
+aspectsProperty['CellularHardware']=['status'];
+aspectsProperty['CellularNetwork']=['isInRoaming', 'signalStrength', 'operatorName'];
+aspectsProperty['Device']=['imei', 'model', 'version', 'vendor'];
+aspectsProperty['Display']=['resolutionHeight', 'pixelAspectRatio', 'dpiY', 'resolutionWidth', 'dpiX', 'colorDepth'];
+aspectsProperty['MemoryUnit']=['size', 'removable', 'availableSize'];
+aspectsProperty['OperatingSystem']=['language', 'version', 'name', 'vendor'];
+aspectsProperty['WebRuntime']=['wacVersion', 'supportedImageFormats', 'version', 'name', 'vendor'];
+aspectsProperty['WiFiHardware']=['status'];
+aspectsProperty['WiFiNetwork']=['ssid', 'signalStrength', 'networkStatus'];
+
+var wrongProperty=['', 'abc'];
+
+var aspectsComponent=Object();
+aspectsComponent['Battery']=['_default'];
+aspectsComponent['CellularHardware']=['_default'];
+aspectsComponent['CellularNetwork']=['_default'];
+aspectsComponent['Device']=['_default'];
+aspectsComponent['Display']=['_default', '_active'];
+aspectsComponent['MemoryUnit']=['_default'];
+aspectsComponent['OperatingSystem']=['_active', '_default'];
+aspectsComponent['WebRuntime']=['_active', '_default'];
+aspectsComponent['WiFiHardware']=['_default'];
+aspectsComponent['WiFiNetwork']=['_default'];
+
+//callbacks;
+function emptyCallback() {
+    jsPrint("empty callback");
+}
+
+function onValueRetrieved(value) {
+    jsPrint("!!!!! value=" + value);
+    TestEngine.test("return value is valid", (value != null));
+}
+
+function onError (error) {
+    TestEngine.test("onError", false);
+}
+
+//DevStatus001;
+function presenceTest()
+{
+    TestEngine.test("Checking deviceapis object", deviceapis);
+    TestEngine.test("Checking Devicestatus object", DevStatusObj);
+
+    TestEngine.test("Checking type of getComponents", isFunction(DevStatusObj.getComponents));
+    TestEngine.test("Checking type of isSupported", isFunction(DevStatusObj.isSupported));
+    TestEngine.test("Checking type of getPropertyValue", isFunction(DevStatusObj.getPropertyValue));
+    TestEngine.test("Checking type of watchPropertyChange", isFunction(DevStatusObj.watchPropertyChange));
+    TestEngine.test("Checking type of clearPropertyChange", isFunction(DevStatusObj.clearPropertyChange));
+}
+
+//DevStatus002;
+function getCompomentInvalidParametersTest() {
+    TestEngine.catchErrorType("code", 17, DevStatusObj, "getComponents");
+
+    try {
+        DevStatusObj.getComponents(undefined);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getComponents(null);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getComponents(1234);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+}
+
+//DevStatus003;
+function isSupportedInvalidParametersTest() {
+    TestEngine.catchErrorType("code", 17, DevStatusObj, "isSupported");
+    try {
+        var stat = DevStatusObj.isSupported(undefined);
+        TestEngine.test("exception should not be thrown", stat == false);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        var stat = DevStatusObj.isSupported(null);
+        TestEngine.test("exception should not be thrown", stat == false);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        var stat = DevStatusObj.isSupported(1234);
+        TestEngine.test("exception should not be thrown", stat == false);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+}
+
+//DevStatus004;
+function getPropertyValueInvalidArgumentsTest() {
+    var onInvalidValueError = function (error) {
+        TestEngine.test("INVALID_VALUES_ERR", error.code == error.INVALID_VALUES_ERR);
+    }
+    var failedSuccess = function (value) {
+        TestEngine.logErr("Success should not be called");
+    }
+    var cbObjInvalidErr = TestEngine.registerCallback("BatterybatteryLeveltest",
+        failedSuccess,
+        onInvalidValueError,
+        6);
+
+    try {
+        DevStatusObj.getPropertyValue(null, null,{
+            property:"batteryLevel",
+            aspect:"Battery"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(null, cbObjInvalidErr.errorCallback,{
+            property:"batteryLevel",
+            aspect:"Battery"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(cbObjInvalidErr.successCallback, cbObjInvalidErr.errorCallback, 1);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(cbObjInvalidErr.successCallback, cbObjInvalidErr.errorCallback, {
+            property:"batteryLevel"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(cbObjInvalidErr.successCallback, cbObjInvalidErr.errorCallback, {
+            property:"batteryLevel",
+            aspect:"invalid"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(cbObjInvalidErr.successCallback, cbObjInvalidErr.errorCallback, {
+            aspect:"invalid"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(cbObjInvalidErr.successCallback, cbObjInvalidErr.errorCallback, {
+            invalid1:"",
+            invalid2:""
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+}
+
+//DevStatus005;
+function watchPropertyChangeInvalidParametersTest() {
+
+    var callbackFunction = function (value) {
+        TestEngine.test("SuccessCallback should not be thrown", false);
+    }
+    var onSuccessError = function(err) {
+        TestEngine.logOK("Error: " + err.code);
+        TestEngine.test("Error callback called as expected", true);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(callbackFunction, onSuccessError, 1);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(null, null, 1);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(callbackFunction, onSuccessError, {
+            property:"batteryLevel"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(callbackFunction, onSuccessError, {
+            property:"batteryLevel",
+            aspect:"invalid"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(callbackFunction, onSuccessError, {
+            invalid:"batteryLevel",
+            invalid:"Battery"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(callbackFunction, onSuccessError, {
+            property:"invalid",
+            aspect:"invalid"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+}
+
+//DevStatus006;
+function clearPropertyChangeInvalidParametersTest() {
+    var callbackFunction = function (value) {
+        TestEngine.logErr("Function called as watch id ???", false);
+    }
+
+    try {
+        DevStatusObj.clearPropertyChange("invalid int value");
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.clearPropertyChange(callbackFunction);
+        TestEngine.test("exception should be thrown", false);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", e.code==e.TYPE_MISMATCH_ERR);
+    }
+
+    try {
+        DevStatusObj.clearPropertyChange(11111111);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+}
+
+//DevStatus007;
+function getComponentsTest() {
+    for (var aspect in aspectsComponent) {
+        var retComponent = DevStatusObj.getComponents(aspect);
+        aspectsComponent[aspect].sort();
+        retComponent.sort();
+        jsPrint("retComponent=" + retComponent);
+        jsPrint("aspectsComponent[aspect]="+aspectsComponent[aspect]);
+        TestEngine.test("length of component for aspect = " + aspect + "is proper", retComponent.length == aspectsComponent[aspect].length);
+
+        for (var i =0; i<retComponent.length; i++) {
+            TestEngine.test("component for aspect " + aspect + " table is equal", retComponent[i] == aspectsComponent[aspect][i]);
+        }
+    }
+}
+
+//DevStatus008;
+function isSupportedTest() {
+    //aspect check;
+    for (var aspect in aspectsProperty) {
+        TestEngine.test("Aspect " + aspect + " check", DevStatusObj.isSupported(aspect));
+    }
+    TestEngine.test("Aspect empty check", !DevStatusObj.isSupported(""));
+    TestEngine.test("Aspect random abc check", !DevStatusObj.isSupported("abc"));
+
+    //aspect and property check;
+    for (var aspect in aspectsProperty) {
+        for (var property in aspectsProperty[aspect]) {
+            var propertyName = aspectsProperty[aspect][property];
+            TestEngine.test("Aspect " + aspect + "/" + propertyName + " check", DevStatusObj.isSupported(aspect, propertyName));
+        }
+        TestEngine.test("Aspect " + aspect + "/null check", DevStatusObj.isSupported(aspect, null));
+    }
+
+    //aspect and wrong property check;
+    for (var aspect in aspectsProperty) {
+        for (var property in wrongProperty) {
+            var propertyName = wrongProperty[property];
+            TestEngine.test("Wrong aspect " + aspect + "/" + propertyName  + " check", !DevStatusObj.isSupported(aspect, propertyName ));
+        }
+    }
+}
+
+//DevStatus009-1;
+function getPropertyValueTest1a() {
+    var cbObj = TestEngine.registerCallback("BatterybatteryLeveltest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"batteryLevel",
+            aspect:"Battery"
+        }
+        );
+}
+
+//DevStatus009-1;
+function getPropertyValueTest1b() {
+    var cbObj = TestEngine.registerCallback("BatterybatteryBeingChargedtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"batteryBeingCharged",
+            aspect:"Battery"
+        }
+        );
+}
+
+//DevStatus009-2;
+function getPropertyValueTest2a() {
+    var cbObj = TestEngine.registerCallback("CellularHardwarestatustest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"status",
+            aspect:"CellularHardware"
+        }
+        );
+}
+
+//DevStatus009-3;
+function getPropertyValueTest3a() {
+    var cbObj = TestEngine.registerCallback("CellularNetworkisInRoamingtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"isInRoaming",
+            aspect:"CellularNetwork"
+        }
+        );
+}
+
+//DevStatus009-2;
+function getPropertyValueTest3b() {
+    var cbObj = TestEngine.registerCallback("CellularNetworksignalStrengthtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"signalStrength",
+            aspect:"CellularNetwork"
+        }
+        );
+}
+
+//DevStatus009-2;
+function getPropertyValueTest3c() {
+    var cbObj = TestEngine.registerCallback("CellularNetworkoperatorNametest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"operatorName",
+            aspect:"CellularNetwork"
+        }
+        );
+}
+
+//DevStatus009-4;
+function getPropertyValueTest4a() {
+    var cbObj = TestEngine.registerCallback("Deviceimeitest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"imei",
+            aspect:"Device"
+        }
+        );
+}
+
+//DevStatus009-4;
+function getPropertyValueTest4b() {
+    var cbObj = TestEngine.registerCallback("Devicemodeltest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"model",
+            aspect:"Device"
+        }
+        );
+}
+
+//DevStatus009-4;
+function getPropertyValueTest4c() {
+    var cbObj = TestEngine.registerCallback("Deviceversiontest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"version",
+            aspect:"Device"
+        }
+        );
+}
+
+//DevStatus009-4;
+function getPropertyValueTest4d() {
+    var cbObj = TestEngine.registerCallback("Devicevendortest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"vendor",
+            aspect:"Device"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5a() {
+    var cbObj = TestEngine.registerCallback("DisplayresolutionHeighttest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"resolutionHeight",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5b() {
+    var cbObj = TestEngine.registerCallback("DisplaypixelAspectRatiotest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"pixelAspectRatio",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5c() {
+    var cbObj = TestEngine.registerCallback("DisplaydpiYtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"dpiY",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5d() {
+    var cbObj = TestEngine.registerCallback("DisplayresolutionWidthtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"resolutionWidth",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5e() {
+    var cbObj = TestEngine.registerCallback("DisplaydpiXtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"dpiX",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5f() {
+    var cbObj = TestEngine.registerCallback("DisplaycolorDepthtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"colorDepth",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-6;
+function getPropertyValueTest6a() {
+    var cbObj = TestEngine.registerCallback("MemoryUnitsizetest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"size",
+            aspect:"MemoryUnit"
+        }
+        );
+}
+
+//DevStatus009-6;
+function getPropertyValueTest6b() {
+    var cbObj = TestEngine.registerCallback("MemoryUnitremovabletest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"removable",
+            aspect:"MemoryUnit"
+        }
+        );
+}
+
+//DevStatus009-6;
+function getPropertyValueTest6c() {
+    var cbObj = TestEngine.registerCallback("MemoryUnitavailableSizetest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"availableSize",
+            aspect:"MemoryUnit"
+        }
+        );
+}
+
+//DevStatus009-7;
+function getPropertyValueTest7a() {
+    var cbObj = TestEngine.registerCallback("OperatingSystemlanguagetest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"language",
+            aspect:"OperatingSystem"
+        }
+        );
+}
+
+//DevStatus009-7;
+function getPropertyValueTest7b() {
+    var cbObj = TestEngine.registerCallback("OperatingSystemversiontest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"version",
+            aspect:"OperatingSystem"
+        }
+        );
+}
+
+//DevStatus009-7;
+function getPropertyValueTest7c() {
+    var cbObj = TestEngine.registerCallback("OperatingSystemnametest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"name",
+            aspect:"OperatingSystem"
+        }
+        );
+}
+
+//DevStatus009-7;
+function getPropertyValueTest7d() {
+    var cbObj = TestEngine.registerCallback("OperatingSystemvendortest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"vendor",
+            aspect:"OperatingSystem"
+        }
+        );
+}
+
+//DevStatus009-8;
+function getPropertyValueTest8a() {
+    var cbObj = TestEngine.registerCallback("WebRuntimeversiontest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"version",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+//DevStatus009-8;
+function getPropertyValueTest8b() {
+    var cbObj = TestEngine.registerCallback("WebRuntimenametest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"name",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+//DevStatus009-8;
+function getPropertyValueTest8c() {
+    var cbObj = TestEngine.registerCallback("WebRuntimevendortest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"vendor",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+//DevStatus009-8;
+function getPropertyValueTest8d() {
+    var cbObj = TestEngine.registerCallback("WebRuntimewacVersiontest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"wacVersion",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+//DevStatus009-8;
+function getPropertyValueTest8e() {
+    var cbObj = TestEngine.registerCallback("WebRuntimesupportedImageFormatstest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"supportedImageFormats",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+//DevStatus009-9;
+function getPropertyValueTest9a() {
+    var cbObj = TestEngine.registerCallback("WiFiHardwarestatustest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"status",
+            aspect:"WiFiHardware"
+        }
+        );
+}
+
+//DevStatus009-10;
+function getPropertyValueTest10a() {
+    var cbObj = TestEngine.registerCallback("WiFiNetworkssidtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"ssid",
+            aspect:"WiFiNetwork"
+        }
+        );
+}
+
+//DevStatus009-10;
+function getPropertyValueTest10b() {
+    var cbObj = TestEngine.registerCallback("WiFiNetworksignalStrengthtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"signalStrength",
+            aspect:"WiFiNetwork"
+        }
+        );
+}
+
+//DevStatus009-10;
+function getPropertyValueTest10c() {
+    var cbObj = TestEngine.registerCallback("WiFiNetworknetworkStatustest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"networkStatus",
+            aspect:"WiFiNetwork"
+        }
+        );
+}
+
+function onCellidRetrieved(value) {
+    jsPrint("!!!!! mcc=" + value.mcc);
+    jsPrint("!!!!! mnc=" + value.mnc);
+    jsPrint("!!!!! cellid=" + value.cellid);
+    jsPrint("!!!!! lac=" + value.lac);
+    jsPrint("!!!!! rat=" + value.rat);
+    TestEngine.test("success callback executed", (value != null));
+}
+
+//DevStatus-extra;
+function getPropertyValueTestCellid() {
+    var cbObj = TestEngine.registerCallback("CellularNetworkcellidtest",
+        onCellidRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"cellid",
+            aspect:"CellularNetwork"
+        }
+        );
+}
+
+//DevStatus010;
+function watchClearPropertyChangeTest() {
+    var watcherId1 = 0;
+    var watcherId2 = 0;
+    var watcherId3 = 0;
+
+    var callbackFunction1 = function (value) {
+        TestEngine.test("Callback 1 called: " +value, true);
+        DevStatusObj.clearPropertyChange(watcherId1);
+
+    }
+    var callbackFunction2 = function (value) {
+        TestEngine.test("Callback 2 called: " +value, true);
+        DevStatusObj.clearPropertyChange(watcherId2);
+
+    }
+    var callbackFunction3 = function (value) {
+        TestEngine.test("Callback 3 called: " +value, true);
+        DevStatusObj.clearPropertyChange(watcherId3);
+    }
+
+    var call1 = TestEngine.registerCallback("watchPropertyCallback1", callbackFunction1, onError);
+    var call2 = TestEngine.registerCallback("watchPropertyCallback2", callbackFunction2, onError);
+    var call3 = TestEngine.registerCallback("watchPropertyCallback3", callbackFunction3, onError);
+
+    watcherId1 = DevStatusObj.watchPropertyChange(
+        call1.successCallback,
+        call1.errorCallback,
+        {
+            property:"batteryLevel",
+            aspect:"Battery"
+        },
+
+        {
+            maxNotificationInterval:2000 //every 2 second;
+        }
+        );
+
+    watcherId2 = DevStatusObj.watchPropertyChange(
+        call2.successCallback,
+        call2.errorCallback,
+        {
+            property:"availableSize",
+            aspect:"MemoryUnit"
+        },
+
+        {
+            maxNotificationInterval:1000 //every 1 second;
+        }
+        );
+
+    watcherId3 = DevStatusObj.watchPropertyChange(
+        call3.successCallback,
+        call3.errorCallback,
+        {
+            aspect:"Battery",
+            property:"batteryLevel"
+        },
+
+        {
+            maxNotificationInterval:2000 //every 2 second;
+        }
+        );
+}
+
+function watchClearPropertyChangeTest1() {
+    var watchId = 0;
+    var callbackFunction1 = function (value) {
+        TestEngine.test("Callback called: " + value, true);
+        DevStatusObj.clearPropertyChange(watchId);
+    }
+    var callObj = TestEngine.registerCallback("watchPropertyCallback", callbackFunction1, onError);
+
+    watchId = DevStatusObj.watchPropertyChange(
+        callObj.successCallback,
+        callObj.errorCallback,
+        {
+            property:"version",
+            aspect:"WebRuntime"
+        },
+
+        {
+            maxNotificationInterval:2000 //every 2 second;
+        }
+        );
+}
+
+function watchClearPropertyChangeTest2() {
+    var watchId = 0;
+    var callbackFunction1 = function (value) {
+        TestEngine.test("Callback called: " + value, true);
+        DevStatusObj.clearPropertyChange(watchId);
+    }
+    var callObj = TestEngine.registerCallback("watchPropertyCallback", callbackFunction1, onError);
+
+    watchId = DevStatusObj.watchPropertyChange(
+        callObj.successCallback,
+        callObj.errorCallback,
+        {
+            property:"version",
+            aspect:"WebRuntime"
+        },
+
+        {
+            minNotificationInterval:2000 //every 2 second;
+        }
+        );
+}
+
+function watchClearPropertyChangeTest3() {
+    var watchId = 0;
+    var callbackFunction1 = function (value) {
+        TestEngine.test("Callback called: " + value, true);
+        DevStatusObj.clearPropertyChange(watchId);
+    }
+    var callObj = TestEngine.registerCallback("watchPropertyCallback", callbackFunction1, onError);
+
+    watchId = DevStatusObj.watchPropertyChange(
+        callObj.successCallback,
+        callObj.errorCallback,
+        {
+            property:"version",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+function watchClearPropertyChangeTest4() {
+    var callbackCnt1 = 0;
+
+    var callbackFunction1 = function (value) {
+        jsPrint("callbackFunction1, value = " + value);
+        if (callbackCnt1 == 0) {
+            TestEngine.test("Callback called once", true);
+        } else {
+            TestEngine.test("Callback called more", false);
+        }
+        callbackCnt1++;
+    }
+
+    var callObj = TestEngine.registerCallback("callback counter check",
+        callbackFunction1, onError);
+
+    var watcherId1 = DevStatusObj.watchPropertyChange(
+        callObj.successCallback,
+        callObj.errorCallback,
+        {
+            property:"batteryLevel",
+            aspect:"Battery"
+        },
+
+        {
+            minChangePercent:50
+        }
+        );
+
+    var finalCallback = TestEngine.registerCallback("callback counter check",
+        function() {
+            jsPrint("TimeOut executed, trying to clear watch, id=" + watcherId1);
+
+            DevStatusObj.clearPropertyChange(watcherId1);
+
+            TestEngine.test("there should be invoked callback", callbackCnt1 == 1);
+        }
+        );
+
+    setTimeout(finalCallback.successCallback,
+        2500); //wait before continuing;
+}
+
+function cleaning() {
+    DevStatusObj = null;
+    aspectsProperty = null;
+    wrongProperty = null;
+    aspectsComponent = null;
+    TestEngine.test("null==DevStatusObj", null==DevStatusObj);
+    TestEngine.test("null==aspectsProperty", null==aspectsProperty);
+    TestEngine.test("null==wrongProperty", null==wrongProperty);
+    TestEngine.test("null==aspectsComponent", null==aspectsComponent);
+}
+
+//=============================================================================;
+
+TestEngine.setTestSuiteName("[WAC2.0][Devicestatus]", 10*1000); //5sec time out for callbacks;
+//TestEngine.addTest(true, presenceTest, "[WAC2.0][Devicestatus] Devicestatus functions presence test");
+TestEngine.addTest(true, getPropertyValueTestCellid, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTestCellid");
+//
+//TestEngine.addTest(true, getPropertyValueInvalidArgumentsTest, "[WAC2.0][Devicestatus] Devicestatus invalid argument test (getPropertyValue)");
+//TestEngine.addTest(true, watchPropertyChangeInvalidParametersTest, "[WAC2.0][Devicestatus] Devicestatus invalid argument test (watchPropertyChange)");
+//TestEngine.addTest(true, clearPropertyChangeInvalidParametersTest, "[WAC2.0][Devicestatus] Devicestatus invalid argument test (clearPropertyChange)");
+//TestEngine.addTest(true, getCompomentInvalidParametersTest, "[WAC2.0][Devicestatus] Devicestatus invalid argument test (getCompoment)");
+//TestEngine.addTest(true, isSupportedInvalidParametersTest, "[WAC2.0][Devicestatus] Devicestatus invalid argument test (isSupported)");
+//
+//TestEngine.addTest(true, getComponentsTest, "[WAC2.0][Devicestatus] Devicestatus getComponents");
+//
+//TestEngine.addTest(true, isSupportedTest, "[WAC2.0][Devicestatus] Devicestatus isSupported");
+//
+//TestEngine.addTest(true, getPropertyValueTest1a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest1a");
+//TestEngine.addTest(true, getPropertyValueTest1b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest1b");
+//TestEngine.addTest(true, getPropertyValueTest2a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest2a");
+//TestEngine.addTest(true, getPropertyValueTest3a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest3a");
+//TestEngine.addTest(true, getPropertyValueTest3b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest3b");
+//TestEngine.addTest(true, getPropertyValueTest3c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest3c");
+//TestEngine.addTest(true, getPropertyValueTest4a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest4a");
+//TestEngine.addTest(true, getPropertyValueTest4b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest4b");
+//TestEngine.addTest(true, getPropertyValueTest4c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest4c");
+//TestEngine.addTest(true, getPropertyValueTest4d, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest4d");
+//TestEngine.addTest(true, getPropertyValueTest5a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5a");
+//TestEngine.addTest(true, getPropertyValueTest5b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5b");
+//TestEngine.addTest(true, getPropertyValueTest5c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5c");
+//TestEngine.addTest(true, getPropertyValueTest5d, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5d");
+//TestEngine.addTest(true, getPropertyValueTest5e, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5e");
+//TestEngine.addTest(true, getPropertyValueTest5f, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5f");
+//TestEngine.addTest(true, getPropertyValueTest6a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest6a");
+//TestEngine.addTest(true, getPropertyValueTest6b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest6b");
+//TestEngine.addTest(true, getPropertyValueTest6c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest6c");
+//TestEngine.addTest(true, getPropertyValueTest7a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest7a");
+//TestEngine.addTest(true, getPropertyValueTest7b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest7b");
+//TestEngine.addTest(true, getPropertyValueTest7c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest7c");
+//TestEngine.addTest(true, getPropertyValueTest7d, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest7d");
+//TestEngine.addTest(true, getPropertyValueTest8a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest8a");
+//TestEngine.addTest(true, getPropertyValueTest8b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest8b");
+//TestEngine.addTest(true, getPropertyValueTest8c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest8c");
+//TestEngine.addTest(true, getPropertyValueTest8d, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest8d");
+//TestEngine.addTest(true, getPropertyValueTest8e, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest8e");
+//TestEngine.addTest(true, getPropertyValueTest9a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest9a");
+//TestEngine.addTest(true, getPropertyValueTest10a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest10a");
+//TestEngine.addTest(true, getPropertyValueTest10b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest10b");
+//TestEngine.addTest(true, getPropertyValueTest10c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest10c");
+//
+//TestEngine.addTest(true, watchClearPropertyChangeTest, "[WAC2.0][Devicestatus] Devicestatus watchClearPropertyChangeTest");
+//TestEngine.addTest(true, watchClearPropertyChangeTest1, "[WAC2.0][Devicestatus] Devicestatus watchClearPropertyChangeTest1");
+//TestEngine.addTest(true, watchClearPropertyChangeTest2, "[WAC2.0][Devicestatus] Devicestatus watchClearPropertyChangeTest2");
+//TestEngine.addTest(true, watchClearPropertyChangeTest3, "[WAC2.0][Devicestatus] Devicestatus watchClearPropertyChangeTest3");
+//TestEngine.addTest(true, watchClearPropertyChangeTest4, "[WAC2.0][Devicestatus] Devicestatus watchClearPropertyChangeTest4");
+
+TestEngine.addTest(true, cleaning, "[WAC2.0][Devicestatus] Cleaning data");
+
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestFilesystem.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestFilesystem.js
new file mode 100644 (file)
index 0000000..a4a1840
--- /dev/null
@@ -0,0 +1,3435 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+// -------------------------| Globals
+var MAX_PATH_LENGTH = 256;
+
+var LOCATION_SPECIFIERS = new Array(
+    'wgt-package',
+    'wgt-private',
+    'wgt-private-tmp',
+    'documents',
+    'images',
+    'videos',
+    'removable',
+    'downloads'
+);
+
+var TEST_ROOT_LOCATION = 'downloads';
+
+// -------------------------| Error verification prerequisites
+TestEngine.setErrorType(Object);
+TestEngine.setErrorField('code');
+var TYPE_MISMATCH_ERR = 17;
+var IO_ERR = 100;
+var INVALID_VALUES_ERR = 22;
+var SECURITY_ERR = 18;
+var NOT_FOUND_ERR = 8;
+var UNKNOWN_ERR = 0;
+
+// -------------------------| Setting up environment.
+try {
+  function on_resolve_error(err) { }
+  function on_resolve_success(file) {
+    function on_listFiles_success(files) {
+      for (i = 0; i < files.length; ++i) {
+        if (files[i].name.match(/^test_wac20_filesystem_/)) {
+          files[i].isDirectory ? deleteDirectory(file, files[i]) : deleteFile(file, files[i]);
+        }
+      }
+    }
+    function on_listFiles_error(err) {
+      TestEngine.log("Error while listing files.");
+    }
+    file.listFiles(on_listFiles_success, on_listFiles_error);
+  }
+  deviceapis.filesystem.resolve(on_resolve_success, on_resolve_error, TEST_ROOT_LOCATION);
+}
+catch (e) {
+  TestEngine.log("Exception while setting up environment.");
+}
+
+// -------------------------| Tests
+// WAC2-FILESYSTEM-001: Check filesystem manager properties.
+function test_filesystem_properties_001() {
+  var props = new Array();
+  props.push(new Array('maxPathLength', MAX_PATH_LENGTH, 0, true, TestEngine.NUMBER));
+  TestEngine.testProperties(deviceapis.filesystem, props);
+}
+
+// WAC2-FILESYSTEM-002: Resolve a file.
+function test_filesystem_resolve_002() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) { TestEngine.test("resolve()", isFileObject(file));}
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-003: Resolve a non-existent file.
+function test_filesystem_resolve_003() {
+  function on_resolve_error(err) {
+    TestEngine.test("resolve() non-existent file [IO_ERR]", (err.code == IO_ERR));
+  }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve() non-existent file [IO_ERR]", false);
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, "locationdd");
+}
+
+// WAC-FILESYSTEM-004: List files from root directory.
+function test_file_listFiles_004() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles() [" + err.code + "]", false);
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", isArray(files));
+    }
+    var cb = TestEngine.registerCallback("listFiles", on_listFiles_success, on_listFiles_error);
+    file.listFiles(cb.successCallback, cb.errorCallback);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-005: Open file in read mode.
+function test_file_open_005() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      deleteFile(file, file2);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    var stream = file2.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-006: Open file in write mode.
+function test_file_open_006() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file2 = file.createFile(getFileName());
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      deleteFile(file, file2);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    var stream = file2.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-007: Open file in append mode.
+function test_file_open_007() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      deleteFile(file, file2);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    var stream = file2.openStream(cb.successCallback, cb.errorCallback, "a", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-008: Call open function with invalid value of parameter 'mode'.
+function test_file_open_error_008() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    function on_openStream_error(err) {
+      TestEngine.test("Calling openStream() with invalid mode.", err.code === err.INVALID_VALUES_ERR);
+      deleteFile(file, file2);
+    }
+    function on_openStream_success(fs) {
+      TestEngine.test("Calling openStream() with invalid mode.", false);
+      fs.close();
+      deleteFile(file, file2);
+    }
+    var file2 = file.createFile(getFileName());
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file2.openStream(cb.successCallback, cb.errorCallback, "x", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-009: Call open function with invalid value of parameter 'encoding'.
+function test_file_open_error_009() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    function on_openStream_error(err) {
+      TestEngine.test("Calling openStream() with invalid encoding.", err.code === err.INVALID_VALUES_ERR);
+      deleteFile(file, file2);
+    }
+    function on_openStream_success(fs) {
+      TestEngine.test("Calling openStream() with invalid encoding.", false);
+      fs.close();
+      deleteFile(file, file2);
+    }
+    var file2 = file.createFile(getFileName());
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file2.openStream(cb.successCallback, cb.errorCallback, "r", "cp-1250");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-010: Copy file w/o overwrite.
+function test_file_copyTo_010() {
+  var g_file = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteFile(file, g_file);
+    }
+    function on_copyTo_success(file2) {
+      TestEngine.test("copyTo()", isFile(file2));
+      deleteFile(file, file2);
+      deleteFile(file, g_file);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    file.copyTo(cb.successCallback, cb.errorCallback, g_file.fullPath, file.fullPath + "/" + getFileName(), false);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-011: Copy file w/o overwrite when destination exists.
+function test_file_copyTo_error_011() {
+  var g_file = null;
+  var g_dest = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_dest = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_dest));
+
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteFile(file, g_file);
+      deleteFile(file, g_dest);
+    }
+    function on_copyTo_success(file2) {
+      TestEngine.test("copyTo()", false);
+      deleteFile(file, file2);
+      deleteFile(file, g_file);
+      deleteFile(file, g_dest);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    file.copyTo(cb.successCallback, cb.errorCallback, g_file.fullPath, file.fullPath + "/" + g_dest.name, false);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-012: Copy file with overwrite when destination exists.
+function test_file_copyTo_012() {
+  var g_file = null;
+  var g_dest = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_dest = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_dest));
+
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteFile(file, g_file);
+      deleteFile(file, g_dest);
+    }
+    function on_copyTo_success(file2) {
+      TestEngine.test("copyTo()", isFile(file2));
+      deleteFile(file, file2);
+      deleteFile(file, g_file);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    file.copyTo(cb.successCallback, cb.errorCallback, g_file.fullPath, file.fullPath + "/" + g_dest.name, true);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-013: Create file.
+function test_file_createFile_013() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file1 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file1));
+    deleteFile(file, file1);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-014: Create file with invalid characters in path.
+function test_file_createFile_error_014() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.log("Calling createFile() with invalid characters in path. [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file, "createFile", "!@#$%^&*(");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-015: Create file when it already exists.
+function test_file_createFile_error_015() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file1 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file1));
+    TestEngine.log("Calling createFile() with path that already exists. [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file, "createFile", file1.name);
+    deleteFile(file, file1);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-016: Create file in file instead of directory.
+function test_file_createFile_error_016() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file1 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file1));
+    TestEngine.log("Calling createFile() on file object. [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file1, "createFile", getFileName());
+    deleteFile(file, file1);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-017: Create file with invalid path componenet - "..".
+function test_file_createFile_error_017() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.testPresetError(
+        "Calling createFile() with invalid path component - \"..\".",
+        function(){file.createFile("../testFile_021");},
+        INVALID_VALUES_ERR
+    );
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-018: Create directory.
+function test_file_createDirectory_018() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+    deleteDirectory(file, dir);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-019: Create directory with invalid character in path.
+function test_file_createDirectory_error_019() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.log("Calling createDirectory() with invalid character in path. - [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file, "createDirectory", "!@#$%^&*(");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-020: Create directory when it already exists.
+function test_file_createDirectory_error_020() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+    TestEngine.log("Calling createDirectory() with path that already exists. - [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file, "createDirectory", dir.name);
+    deleteDirectory(file, dir);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-021: Create directory in file instead of directory.
+function test_file_createDirectory_error_021() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file1 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file1));
+    TestEngine.log("Calling createDirectory() on file object. - [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file1, "createDirectory", getDirName());
+    deleteFile(file, file1);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-022: Create file with invalid path componenet - "..".
+function test_file_createDirectory_error_022() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.testPresetError(
+      "Calling createDirectory() with invalid path component - \"..\".",
+      function(){file.createDirectory("../" + getDirName());},
+      INVALID_VALUES_ERR
+    );
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-023: Move file w/o overwrite.
+function test_file_moveTo_023() {
+  var g_file = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", false);
+      deleteFile(file, g_file);
+    }
+    function on_moveTo_success(file1) {
+      TestEngine.test("moveTo()", true);
+      deleteFile(file, file1);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    file.moveTo(cb.successCallback, cb.errorCallback, g_file.fullPath, file.fullPath + "/" + getFileName(), false);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-024: Move file w/o overwrite when destination exists.
+function test_file_moveTo_error_024() {
+  var g_file = null;
+  var g_dest = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_dest = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_dest));
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [IO_ERR]", (err.code == IO_ERR));
+      deleteFile(file, g_file);
+      deleteFile(file, g_dest);
+    }
+    function on_moveTo_success(file1) {
+      TestEngine.test("moveTo()", false);
+      deleteFile(file, file1);
+      deleteFile(file, g_dest);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    file.moveTo(cb.successCallback, cb.errorCallback, g_file.fullPath, g_dest.fullPath, false);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-025: Move file with overwrite when destination exists.
+function test_file_moveTo_025() {
+  var g_file = null;
+  var g_dest = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_dest = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_dest));
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", false);
+      deleteFile(file, g_file);
+      deleteFile(file, g_dest);
+    }
+    function on_moveTo_success(file1) {
+      TestEngine.test("moveTo()", isFile(file1));
+      deleteFile(file, file1);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    file.moveTo(cb.successCallback, cb.errorCallback, g_file.fullPath, g_dest.fullPath, true);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-026: Delete a file.
+function test_file_deleteFile_026() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    deleteFile(file, f);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-027: Call deleteFile() on a directory.
+function test_file_deleteFile_error_027() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+    function on_deleteFile_error(err) {
+      TestEngine.test("deleteFile() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+      deleteDirectory(file, dir);
+    }
+    function on_deleteFile_success() {
+      TestEngine.test("deleteFile()", false);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+    file.deleteFile(cb.successCallback, cb.errorCallback, dir.fullPath);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-028: Call deleteFile() on a file.
+function test_file_deleteFile_error_028() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file1 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file1));
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    function on_deleteFile_error(err) {
+      TestEngine.test("Call deleteFile() on a file. [IO_ERR]", (err.code == IO_ERR));
+      deleteFile(file, file1);
+      deleteFile(file, file2);
+    }
+    function on_deleteFile_success() {
+      TestEngine.test("Call deleteFile() on a file. [IO_ERR]", false);
+      deleteFile(file, file2);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+    file1.deleteFile(cb.successCallback, cb.errorCallback, file2.fullPath);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-029: Call deleteFile() on the same file twice.
+function test_file_deleteFile_error_029() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    deleteFile(file, f);
+    function on_deleteFile_error(err) {
+      TestEngine.test("Call deleteFile() on a file that has already been deleted. [IO_ERR]", (err.code == IO_ERR));
+    }
+    function on_deleteFile_success() {
+      TestEngine.test("Call deleteFile() on a file that has already been deleted. [IO_ERR]", false);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+    file.deleteFile(cb.successCallback, cb.errorCallback, f.fullPath);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-030: Call deleteFile() on opened file.
+function test_file_deleteFile_error_030() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      function on_deleteFile_error(err) {
+        TestEngine.test("Call deleteFile() on opened file. [IO_ERR]", (err.code == IO_ERR));
+        stream.close();
+        deleteFile(file, f);
+      }
+      function on_deleteFile_success() {
+        TestEngine.test("Call deleteFile() on opened file. [IO_ERR]", false);
+        stream.close();
+      }
+      var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+      file.deleteFile(cb.successCallback, cb.errorCallback, f.fullPath);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-031: Delete a directory.
+function test_file_deleteDirectory_031() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+    deleteDirectory(file, dir);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-032: Call deleteDirectory() on a file.
+function test_file_deleteDirectory_error_032() {
+  var g_file = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("Call deleteDirectory() on a file. [IO_ERR] [" + err.code + "]", (err.code == IO_ERR));
+      deleteFile(file, g_file);
+    }
+    function on_deleteDirectory_success(file) {
+      TestEngine.test("deleteDirectory()", false);
+      deleteFile(file, g_file);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+    g_file.deleteDirectory(cb.successCallback, cb.errorCallback, "foo", true);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-033: Call deleteDirectory() on the same directory twice.
+function test_file_deleteDirectory_error_033() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+      function on_deleteDirectory2_error(err) {
+        TestEngine.test("Call deleteDirectory() on a dir that has already been deleted. [IO_ERR] [" + err.code + "]", (err.code == IO_ERR));
+      }
+      function on_deleteDirectory2_success(file) {
+        TestEngine.test("deleteDirectory()", false);
+      }
+    deleteDirectory(file, dir);
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory2_success, on_deleteDirectory2_error);
+    file.deleteDirectory(cb.successCallback, cb.errorCallback, dir.fullPath, true);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-034: Call deleteDirectory() non-recursively on non-empty directory.
+function test_file_deleteDirectory_error_034() {
+  var g_dir = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(g_dir));
+    TestEngine.test("createFile()", isFile(g_dir.createFile(getFileName())));
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("Call deleteDirectory() non-recursively on non-empty dir. [IO_ERR]", (err.code == IO_ERR));
+      deleteDirectory(file, g_dir);
+    }
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", false);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+    file.deleteDirectory(cb.successCallback, cb.errorCallback, g_dir.fullPath, false);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-035: Call write()/read() on a stream.
+function test_filestream_write_read_035() {
+  var test_string = "It's alive! Alive!";
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream1) {
+      TestEngine.test("openStream()", isFilestream(stream1));
+      stream1.write(test_string);
+      stream1.close();
+      function on_openStream1_success(r_stream) {
+        TestEngine.test("openStream()", isFilestream(r_stream));
+        var read_string = r_stream.read(test_string.length);
+        r_stream.close();
+        TestEngine.test("write()/read()", (read_string === test_string));
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-036: Call read() on a closed stream.
+function test_filestream_read_error_036() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call read() on a closed stream. [IO_ERR]",
+        function(){stream.read(3);},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-037: Call read() on a stream with EOF flag set.
+function test_filestream_read_error_037() {
+  var test_string = "It's alive! Alive!";
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_string);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_string = stream1.read(test_string.length);
+        TestEngine.testPresetError(
+          "Call read() on stream with EOF set. [IO_ERR]",
+          function(){stream1.read(1);},
+          IO_ERR
+        );
+        stream1.close();
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-038: Call openStream() on a directory.
+function test_file_open_error_038() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+    function on_openStream_success(stream) {
+      TestEngine.test("Call openStream() on a directory.", false);
+      stream.close();
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("Call openStream() on a directory. [IO_ERR]", (err.code == IO_ERR));
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    dir.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    deleteDirectory(file, dir);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-040: Call read() on write-only stream.
+function test_filestream_read_error_040() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call read() on write-only stream. [IO_ERR]",
+        function(){stream.read(0);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-041: Call write() on a closed stream.
+function test_filestream_write_error_041() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call write() on a closed stream. [IO_ERR]",
+        function(){stream.write('test');},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-042: Call write() on read-only stream.
+function test_filestream_write_error_042() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call write() on read-only stream. [IO_ERR]",
+        function(){stream.write('test');},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-043
+// Parameters: stringData = array
+// Result: Test passes (toString() called on JS Array).
+function test_filestream_write_error_043() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(new Array('t','e','s','t'));
+      TestEngine.test("write()", true);
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-044: Call write() w/o argument.
+function test_filestream_write_error_044() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call write() w/o argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.write();},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-045: Call read() with invalid argument type.
+function test_filestream_read_error_045() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.test("read()", stream.read('should be a number') == '');
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-046: Call read() w/o argument.
+function test_filestream_read_error_046() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call read() w/o argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.read();},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-047: Call writeBytes()/readBytes() on a stream.
+function test_filestream_writeBytes_readBytes_047() {
+  var test_array = new Array(1, 2, 3, 4);
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBytes(test_array);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_array = stream1.readBytes(test_array.length);
+        stream1.close();
+        var cmp = false;
+        if (test_array.length == read_array.length) {
+          cmp = true;
+          for (i = 0; i < test_array.length; ++i) {
+            if (test_array[i] != read_array[i]) {
+              cmp = false;
+              break;
+            }
+          }
+        }
+        TestEngine.test("writeBytes()/readBytes()", cmp);
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-048: Call readBytes() on a closed stream.
+function test_filestream_readBytes_error_048() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call readBytes() on a closed stream. [IO_ERR]",
+        function(){stream.readBytes(3);},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-049: Call readBytes() on a stream with EOF flag set.
+function test_filestream_readBytes_error_049() {
+  var test_array = new Array(1, 2, 3, 4);
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBytes(test_array);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_array = stream1.readBytes(100);
+        TestEngine.testPresetError(
+          "Call readBytes() on stream with EOF set. [IO_ERR]",
+          function(){stream1.readBytes(1);},
+          IO_ERR
+        );
+        stream1.close();
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-051: Call readBytes() on write-only stream.
+function test_filestream_readBytes_error_051() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call readBytes() on write-only stream. [IO_ERR]",
+        function(){stream.readBytes(0);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-052
+// Parameters: byteCount = string
+// Result: Test passes (conversion exception).
+function test_filestream_readBytes_error_052() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.test("readBytes()", stream.readBytes('should be a number').length == 0);
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-053: Call readBytes() w/o argument.
+function test_filestream_readBytes_error_053() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call read() w/o argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.readBytes();},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-054: Call writeBytes() on a closed stream.
+function test_filestream_writeBytes_error_054() {
+  var test_array = new Array(1, 2, 3, 4);
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call writeBytes() on a closed stream. [IO_ERR]",
+        function(){stream.writeBytes(test_array);},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-055: Call writeBytes() on read-only stream.
+function test_filestream_writeBytes_error_055() {
+  var test_array = new Array(1, 2, 3, 4);
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call writeBytes() on read-only stream. [IO_ERR]",
+        function(){stream.writeBytes(test_array);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-056: Call writeBytes() with invalid argument type.
+function test_filestream_writeBytes_error_056() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call writeBytes() with invalid argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.writeBytes(3);},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-057: Call writeBytes() w/o argument.
+function test_filestream_writeBytes_057() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBytes();
+      stream.close();
+
+      function on_openStream_read_success(stream) {
+        TestEngine.test("openStream()", isFilestream(stream));
+        var readData = stream.readBytes(256);
+        stream.close();
+        TestEngine.test("readBytes()", isArray(readData) && readData.length == 0);
+        deleteFile(file, f);
+      }
+
+      var cb = TestEngine.registerCallback("openStream", on_openStream_read_success, on_openStream_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-058: Call writeBase64()/readBase64() on a stream.
+function test_filestream_writeBase64_readBase64_058() {
+  var test_base64 = 'dGVzdA==';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBase64(test_base64);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_base64 = stream1.readBase64(100);
+        stream1.close();
+        TestEngine.test("writeBase64()/readBase64()", (test_base64 === read_base64));
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-059: Call writeBase64()/read() on a stream.
+function test_filestream_writeBase64_read_059() {
+  var test_base64 = 'dGVzdA==';
+  var test_string = 'test';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBase64(test_base64);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_string = stream1.read(test_string.length);
+        stream1.close();
+        TestEngine.test("writeBase64()/read()", (test_string === read_string));
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-060: Call write()/readBase64() on a stream.
+function test_filestream_write_readBase64_060() {
+  var test_base64 = 'dGVzdA==';
+  var test_string = 'test';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_string);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_base64 = stream1.readBase64(100);
+        stream1.close();
+        TestEngine.test("write()/readBase64()", (test_base64 === read_base64));
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-061: Call readBase64() on a closed stream.
+function test_filestream_readBase64_error_061() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call readBase64() on a closed stream. [IO_ERR]",
+        function(){stream.readBase64(3);},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-062: Call readBase64() on a stream with EOF flag set.
+function test_filestream_readBase64_error_062() {
+  var test_base64 = 'dGVzdA==';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBase64(test_base64);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_base64 = stream1.readBase64(100);
+        TestEngine.testPresetError(
+          "Call readBase64() on stream with EOF set. [IO_ERR]",
+          function(){stream1.readBase64(1);},
+          IO_ERR
+        );
+        stream1.close();
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-064: Call readBase64() on write-only stream.
+function test_filestream_readBase64_error_064() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call readBase64() on write-only stream. [IO_ERR]",
+        function(){stream.readBase64(0);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-065
+// Parameters: byteCount = string
+// Result: Test passes (empty string).
+function test_filestream_readBase64_error_065() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.test("readBase64()", stream.readBase64('should be a number') == '');
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-066: Call readBase64() w/o argument.
+function test_filestream_readBase64_error_066() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call readBase64() w/o argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.readBase64();},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-067: Call writeBase64() on a closed stream.
+function test_filestream_writeBase64_error_067() {
+  var test_base64 = 'dGVzdA==';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call writeBase64() on a closed stream. [IO_ERR]",
+        function(){stream.writeBase64(test_base64);},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-068: Call writeBase64() on read-only stream.
+function test_filestream_writeBase64_error_068() {
+  var test_base64 = 'dGVzdA==';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call writeBase64() on read-only stream. [IO_ERR]",
+        function(){stream.writeBase64(test_base64);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-069
+// Parameters: base64Data = invalid value
+// Result: IO_ERR thrown in place.
+function test_filestream_writeBase64_error_069() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call writeBase64() with invalid argument.",
+        function(){stream.writeBase64(3);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-070: Call writeBase64() w/o argument.
+function test_filestream_writeBase64_error_070() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call writeBase64() w/o argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.writeBase64();},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-071: Call createFile() on node resolved in read-only mode.
+function test_file_createFile_error_071() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.testPresetError(
+      "Call createFile() on read-only node. [SECURITY_ERR]",
+      function() {
+        var f = file.createFile(getFileName());
+        deleteFile(file, f);
+      },
+      SECURITY_ERR
+    );
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "r");
+}
+
+// WAC-FILESYSTEM-072: Call deleteFile() on node resolved in read-only mode.
+function test_file_deleteFile_error_072() {
+  var filename = getFileName();
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("createFile()", isFile(file.createFile(filename)));
+
+    function on_resolve1_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+    function on_resolve1_success(file) {
+      var f = file.resolve(filename);
+      TestEngine.test("resolve()", isFile(f));
+
+      function on_deleteFile_error(err) {
+        TestEngine.test("Call deleteFile() on read-only node. [SECURITY_ERR]", (err.code == SECURITY_ERR));
+        function on_resolve2_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+        function on_resolve2_success(file) {
+          var f = file.resolve(filename);
+          TestEngine.test("resolve()", isFile(f));
+          deleteFile(file, f);
+        }
+        var cb = TestEngine.registerCallback("resolve", on_resolve2_success, on_resolve2_error);
+        deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+      }
+      function on_deleteFile_success() {
+        TestEngine.test("Call deleteFile() on read-only node. [SECURITY_ERR]", false);
+      }
+      var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+      file.deleteFile(cb.successCallback, cb.errorCallback, f.fullPath);
+    }
+    var cb = TestEngine.registerCallback("resolve", on_resolve1_success, on_resolve1_error);
+    deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "r");
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+}
+
+// WAC-FILESYSTEM-073: Call deleteDirectory() on node resolved in read-only mode.
+function test_file_deleteDirectory_error_073() {
+  var dirname = getDirName();
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("createDirectory()", isDir(file.createDirectory(dirname)));
+
+    function on_resolve1_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+    function on_resolve1_success(file) {
+      var dir = file.resolve(dirname);
+      TestEngine.test("resolve()", isDir(dir));
+
+      function on_deleteDirectory_error(err) {
+        TestEngine.test("Call deleteDirectory() on read-only node. [SECURITY_ERR]", (err.code == SECURITY_ERR));
+        function on_resolve2_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+        function on_resolve2_success(file) {
+          var dir = file.resolve(dirname);
+          TestEngine.test("resolve()", isDir(dir));
+          deleteDirectory(file, dir);
+        }
+        var cb = TestEngine.registerCallback("resolve", on_resolve2_success, on_resolve2_error);
+        deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+      }
+      function on_deleteDirectory_success() {
+        TestEngine.test("Call deleteDirectory() on read-only node. [SECURITY_ERR]", false);
+      }
+      var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+      file.deleteDirectory(cb.successCallback, cb.errorCallback, dir.fullPath, true);
+    }
+    var cb = TestEngine.registerCallback("resolve", on_resolve1_success, on_resolve1_error);
+    deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "r");
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+}
+
+// WAC-FILESYSTEM-074: Call moveTo() on node resolved in read-only mode.
+function test_file_moveTo_error_074() {
+  var src_filename = getFileName();
+  var dst_filename = getFileName();
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(src_filename);
+    TestEngine.test("createFile()", isFile(f));
+
+    function on_resolve1_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+    function on_resolve1_success(file) {
+      var f = file.resolve(src_filename);
+      TestEngine.test("resolve()", isFile(f));
+
+      function on_moveTo_error(err) {
+        TestEngine.test("Call moveTo() on read-only mode. [SECURITY_ERR]", (err.code == SECURITY_ERR));
+        function on_resolve2_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+        function on_resolve2_success(file) {
+          var f = file.resolve(src_filename);
+          TestEngine.test("resolve()", isFile(f));
+          deleteFile(file, f);
+        }
+        var cb = TestEngine.registerCallback("resolve", on_resolve2_success, on_resolve2_error);
+        deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+      }
+      function on_moveTo_success(file1) {
+        TestEngine.test("Call moveTo() on read-only mode. [SECURITY_ERR]", false);
+        function on_resolve2_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+        function on_resolve2_success(file) {
+          var f = file.resolve(dst_filename);
+          TestEngine.test("resolve()", isFile(f));
+          deleteFile(file, f);
+        }
+        var cb = TestEngine.registerCallback("resolve", on_resolve2_success, on_resolve2_error);
+        deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+      }
+      var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+      file.moveTo(cb.successCallback, cb.errorCallback, f.fullPath, file.fullPath + '/' + dst_filename, true);
+    }
+    var cb = TestEngine.registerCallback("resolve", on_resolve1_success, on_resolve1_error);
+    deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "r");
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+}
+
+// WAC-FILESYSTEM-075: Call openStream() in write-only mode on node resolved in read-only mode.
+function test_file_openStream_error_075() {
+  var filename = getFileName();
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(filename);
+    TestEngine.test("createFile()", isFile(f));
+
+    function on_resolve1_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+    function on_resolve1_success(r_file) {
+      var f = r_file.resolve(filename);
+      TestEngine.test("resolve()", isFile(f));
+
+      function on_openStream_success(stream) {
+        TestEngine.test("Call openStream() in write-only mode on read-only node. [SECURITY_ERR]", false);
+        stream.close();
+        deleteFile(file, f);
+      }
+      function on_openStream_error(err) {
+        TestEngine.test("Call openStream() in write-only mode on read-only node. [SECURITY_ERR]", (err.code == SECURITY_ERR));
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+    }
+    var cb = TestEngine.registerCallback("resolve", on_resolve1_success, on_resolve1_error);
+    deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "r");
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+}
+
+// WAC-FILESYSTEM-076: Call readAsText() on a file.
+function test_file_readAsText_076() {
+  var test_content = "Ala ma kota";
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      f.readAsText(cb.successCallback, cb.errorCallback, "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-077: Call readAsText() on a directory.
+function test_file_readAsText_error_077() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+
+    function on_readAsText_error(err) {
+      TestEngine.test("Call readAsText() on a directory [IO_ERR]", (err.code == IO_ERR));
+    }
+    function on_readAsText_success(str) {
+      TestEngine.test("Call readAsText() on a directory [IO_ERR]", false);
+    }
+    var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+    dir.readAsText(cb.successCallback, cb.errorCallback, "UTF-8");
+    deleteDirectory(file, dir);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-078: Call readAsText() on a deleted file.
+function test_file_readAsText_error_078() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(root) {
+    var file = root.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file));
+
+    function on_deleteFile_error(err) { TestEngine.test("deleteFile() [" + err.code + "]", false); }
+    function on_deleteFile_success() {
+      function on_readAsText_error(err) {
+        TestEngine.test("Call readAsText() on a deleted file [IO_ERR]", (err.code == IO_ERR));
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("Call readAsText() on a deleted file [IO_ERR]", false);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback, "UTF-8");
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+    root.deleteFile(cb.successCallback, cb.errorCallback, file.fullPath);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-079: Call toUri() on file located in root folder.
+function test_file_toUri_079() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    var uri = f.toURI();
+    TestEngine.test("Call toUri() returns non empty string", isString(uri) && uri.length > 0);
+    TestEngine.log("created uri: " + uri);
+    deleteFile(file, f);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-080: Resolve a file with mode set to null.
+function test_filesystem_resolve_080() {
+  function on_resolve_error(err) {
+    TestEngine.test("resolve()", false);
+  }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", true);
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, null);
+}
+
+// WAC-FILESYSTEM-081: List files with null passed as filter.
+function test_file_listFiles_081() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles() [" + err.code + "]", false);
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", isArray(files));
+    }
+    var cb = TestEngine.registerCallback("listFiles", on_listFiles_success, on_listFiles_error);
+    file.listFiles(cb.successCallback, cb.errorCallback, null);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-082: List files with undefined passed as filter.
+function test_file_listFiles_082() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles() [" + err.code + "]", false);
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", isArray(files));
+    }
+    var cb = TestEngine.registerCallback("listFiles", on_listFiles_success, on_listFiles_error);
+    file.listFiles(cb.successCallback, cb.errorCallback, undefined);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-083
+// Parameters: filter = 1, others = valid
+// Result: Test passes.
+function test_file_listFiles_error_083() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles()", false);
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", isArray(files));
+    }
+    var cb = TestEngine.registerCallback("listFiles", on_listFiles_success, on_listFiles_error);
+    file.listFiles(cb.successCallback, cb.errorCallback, 1);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-084: List files with null passed as success callback.
+function test_file_listFiles_error_084() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", false);
+    }
+    var cb = TestEngine.registerCallback("listFiles", on_listFiles_success, on_listFiles_error);
+    file.listFiles(null, cb.errorCallback);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-085
+// Parameters: successCallback = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_listFiles_error_085() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles()", (err.code == INVALID_VALUES_ERR));
+    }
+    var cb = TestEngine.registerCallback("listFiles", undefined, on_listFiles_error);
+    file.listFiles(cb.successCallback, cb.errorCallback);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-086: List files with both callbacks set to null. Nothing should happen.
+function test_file_listFiles_error_086() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles() [" + err.code + "]", false);
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", false);
+    }
+    // Pass callbacks directly to prevent "widget run timeout".
+    file.listFiles(null, null);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-087: Test optionality of the last parameter.
+function test_file_open_087() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      deleteFile(file, file2);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    var stream = file2.openStream(cb.successCallback, cb.errorCallback, "r");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-088: Test success callback set to null.
+function test_file_open_error_088() {
+  function on_resolve_success(root) {
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    var file = createFileForParent(root);
+    // Pass callbacks directly to prevent "widget run timeout".
+    var cb = TestEngine.registerCallback("openStream", null, on_openStream_error);
+    var stream = file.openStream(null, cb.errorCallback, "r");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-089
+// Parameters: successCallback = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_open_error_089() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    
+    var cb = TestEngine.registerCallback("openStream", undefined, on_openStream_error);
+    var stream = file.openStream(cb.successCallback, cb.errorCallback, "r");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-090: Test passing invalid mode with error callback set to null.
+function test_file_open_error_090() {
+  function on_resolve_success(root) {
+    function on_openStream_success(fs) {
+      TestEngine.test("Calling openStream() with invalid mode.", false);
+      fs.close();
+      deleteFile(root, file);
+    }
+    var file = createFileForParent(root);
+    testNoExceptionWithMessage("openStream()", function() {
+      // Pass callbacks directly to prevent "widget run timeout".
+      file.openStream(on_openStream_success, null, "x", "UTF-8");
+    });
+    deleteFile(root, file);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-091: Call readAsText() w/o specifing encoding parameter.
+function test_file_readAsText_091() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", false);
+        deleteFile(root, file);
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-092: Call readAsText() with encoding parameter set to null.
+function test_file_readAsText_092() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", false);
+        deleteFile(root, file);
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback, null);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-093: Call readAsText() with error callback set to null.
+function test_file_readAsText_093() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, null);
+      file.readAsText(cb.successCallback, null);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-094: Call readAsText() w/o specifing error callback.
+function test_file_readAsText_094() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, null);
+      file.readAsText(cb.successCallback);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-095: Call readAsText() with success callback set to null.
+function test_file_readAsText_error_095() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", null, on_readAsText_error);
+      file.readAsText(null, cb.errorCallback);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-096: Call readAsText() with both callbacks set to null.
+function test_file_readAsText_error_096() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      testNoExceptionWithMessage("readAsText()", function() {
+        file.readAsText(null, null);
+      });
+      deleteFile(root, file);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-097
+// Parameters: successCallback = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_readAsText_error_097() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText()", (err.code == INVALID_VALUES_ERR));
+        deleteFile(root, file);
+      }
+      
+      var cb = TestEngine.registerCallback("readAsText", undefined, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback, "r");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-098: Call readAsText() with invalid encoding parameter.
+function test_file_readAsText_error_098() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+        deleteFile(root, file);
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", false);
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback, "INVALID");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-099: Call deleteDirectory() with error callback set to null.
+function test_file_deleteDirectory_099() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", true);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, null);
+    root.deleteDirectory(cb.successCallback, null, dir.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-100: Call deleteDirectory() with error callback set to null
+//                     and directory set to invalid value.
+function test_file_deleteDirectory_error_100() {
+  function on_resolve_success(root) {
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", false);
+    }
+    testNoExceptionWithMessage("deleteDirectory()", function() {
+      // Pass callbacks directly to prevent "widget run timeout".
+      root.deleteDirectory(on_deleteDirectory_success, null, "../", true);
+    });
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-101: Call deleteDirectory() with success callback set to null.
+function test_file_deleteDirectory_error_101() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("deleteDirectory() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", null, on_deleteDirectory_error);
+    root.deleteDirectory(null, cb.errorCallback, dir.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-102
+// Parameters: successCallback = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_deleteDirectory_error_102() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("deleteDirectory()", (err.code == INVALID_VALUES_ERR));
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", undefined, on_deleteDirectory_error);
+    root.deleteDirectory(cb.successCallback, cb.errorCallback, dir.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-103
+// Parameters: directory = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_deleteDirectory_error_103() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("deleteDirectory()", (err.code == INVALID_VALUES_ERR));
+      deleteDirectory(root, dir);
+    }
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", false);
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+    root.deleteDirectory(cb.successCallback, cb.errorCallback, undefined, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-104
+// Parameters: recursive = undefined, others = valid
+// Result: Test passes.
+function test_file_deleteDirectory_error_104() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("deleteDirectory()", false);
+      deleteDirectory(root, dir);
+    }
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", true);
+    }
+    
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+    root.deleteDirectory(cb.successCallback, cb.errorCallback, dir.fullPath, undefined);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-105: Call deleteDirectory() with directory parameter pointing to a file.
+function test_file_deleteDirectory_error_105() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("deleteDirectory() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+    root.deleteDirectory(cb.successCallback, cb.errorCallback, file.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-106: Call deleteFile() with error callback set to null.
+function test_file_deleteFile_106() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_deleteFile_success() {
+      TestEngine.test("deleteFile()", true);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, null);
+    root.deleteFile(cb.successCallback, null, file.fullPath);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-107: Call deleteFile() with error callback set to null
+//                     and file set to invalid value.
+function test_file_deleteFile_error_107() {
+  function on_resolve_success(root) {
+    function on_deleteFile_success() {
+      TestEngine.test("deleteFile()", false);
+    }
+    testNoExceptionWithMessage("deleteFile()", function() {
+      // Pass callbacks directly to prevent "widget run timeout".
+      root.deleteFile(on_deleteFile_success, null, "../");
+    });
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-108: Call deleteFile() with success callback set to null.
+function test_file_deleteFile_error_108() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_deleteFile_error(err) {
+      TestEngine.test("deleteFile() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", null, on_deleteFile_error);
+    root.deleteFile(null, cb.errorCallback, file.fullPath);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-109
+// Parameters: successCallback = undefined, others valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_deleteFile_error_109() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_deleteFile_error(err) {
+      TestEngine.test("deleteFile()", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", undefined, on_deleteFile_error);
+    root.deleteFile(cb.successCallback, cb.errorCallback, file.fullPath);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-110
+// Parameters: file = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_deleteFile_error_110() {
+  function on_resolve_success(root) {
+    function on_deleteFile_error(err) {
+      TestEngine.test("deleteFile()", (err.code == INVALID_VALUES_ERR));
+    }
+    function on_deleteFile_success() {
+      TestEngine.test("deleteFile()", false);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+    root.deleteFile(cb.successCallback, cb.errorCallback, undefined);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-111
+// Parameters: errorCallback = undefined, others = valid
+// Result: Test passes.
+function test_file_deleteFile_error_111() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_deleteFile_success() {
+      TestEngine.test("deleteFile()", true);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, undefined);
+    root.deleteFile(cb.successCallback, cb.errorCallback, file.fullPath);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-112
+// Parameters: mode = undefined, others = valid
+// Result: Test passes.
+function test_filesystem_resolve_112() {
+  function on_resolve_error(err) {
+   TestEngine.test("resolve() [" + err.code + "]", false);
+  }
+  function on_resolve_success(root) {
+   TestEngine.test("resolve()", true);
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, undefined);
+}
+
+// WAC-FILESYSTEM-113
+// Parameters: encoding = undefined, others = valid
+// Result: Test passes.
+function test_file_readAsText_113() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", false);
+        deleteFile(root, file);
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback, undefined);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-114
+// Parameters: encoding = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_open_114() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", false);
+      stream.close();
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    var stream = file.openStream(cb.successCallback, cb.errorCallback, "r", undefined);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-115
+// Parameters: originFilePath = (empty) directory, overwrite = false
+// Result: Test passes.
+function test_file_copyTo_115() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteDirectory(root, dir);
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", isDir(copy));
+      deleteDirectory(root, copy);
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, dir.fullPath, root.fullPath + "/" + getDirName(), false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-116
+// Parameters: originFilePath = (non-empty) directory, overwrite = false
+// Result: Test passes.
+function test_file_copyTo_116() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    var file = createFileForParent(dir);
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteDirectory(root, dir);
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", isDir(copy));
+      var child = copy.resolve(file.name);
+      TestEngine.test("copyTo()", isFile(child));
+      deleteDirectory(root, copy);
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, dir.fullPath, root.fullPath + "/" + getDirName(), false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-117
+// Parameters: originFilePath = undefined, other params = valid.
+// Result: INVALID_VALUES_ERR thrown via errorCallback.
+function test_file_copyTo_error_117() {
+  function on_resolve_success(root) {
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo()", (err.code == INVALID_VALUES_ERR));
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", false);
+      deleteDirectory(root, copy);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, undefined, root.fullPath + "/" + getDirName(), false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-118
+// Parameters: originFilePath = invalid path, overwrite = false
+// Result: INVALID_VALUES_ERR returned by error callback.
+function test_file_copyTo_error_118() {
+  function on_resolve_success(root) {
+   function on_copyTo_error(err) {
+     TestEngine.test("copyTo() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+   }
+   function on_copyTo_success(copy) {
+     TestEngine.test("copyTo()", false);
+     deleteDirectory(root, copy);
+   }
+   var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+   root.copyTo(cb.successCallback, cb.errorCallback, "../", root.fullPath + "/" + getDirName(), false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-119
+// Parameters: originFilePath = valid file, destinationFilePath = valid directory, overwrite = true
+// Result: Test passes (replacing destination directory with a origin file).
+function test_file_copyTo_119() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    var dir = createDirForParent(root);
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteDirectory(root, dir);
+      deleteFile(root, file);
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", (copy.fullPath == dir.fullPath) && isFile(copy));
+      deleteFile(root, copy);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, file.fullPath, dir.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-120
+// Parameters: originFilePath = valid file, destinationFilePath = valid directory, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_copyTo_error_120() {
+  function on_resolve_success(root) {
+   var file = createFileForParent(root);
+   var dir = createDirForParent(root);
+   function on_copyTo_error(err) {
+     TestEngine.test("copyTo() [" + err.code + "]", (err.code == IO_ERR));
+     deleteDirectory(root, dir);
+     deleteFile(root, file);
+   }
+   function on_copyTo_success(copy) {
+     TestEngine.test("copyTo()", false);
+     deleteFile(root, copy);
+     deleteFile(root, file);
+   }
+   var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+   root.copyTo(cb.successCallback, cb.errorCallback, file.fullPath, dir.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-121
+// Parameters: originFilePath = valid directory, destinationFilePath = valid file, overwrite = true
+// Result: Test passes (replacing destination file with a origin directory).
+function test_file_copyTo_121() {
+  function on_resolve_success(root) {
+   var file = createFileForParent(root);
+   var dir = createDirForParent(root);
+   var child = createFileForParent(dir);
+   function on_copyTo_error(err) {
+     TestEngine.test("copyTo() [" + err.code + "]", false);
+     deleteDirectory(root, dir);
+     deleteFile(root, file);
+   }
+   function on_copyTo_success(copy) {
+     TestEngine.test("copyTo()", (copy.fullPath == file.fullPath) && isDir(copy));
+     TestEngine.test("resolve()", isFile(copy.resolve(child.name)));
+     deleteDirectory(root, copy);
+     deleteDirectory(root, dir);
+   }
+   var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+   root.copyTo(cb.successCallback, cb.errorCallback, dir.fullPath, file.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-122
+// Parameters: originFilePath = valid directory, destinationFilePath = valid file, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_copyTo_error_122() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    var dir = createDirForParent(root);
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteDirectory(root, dir);
+      deleteFile(root, file);
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", false);
+      deleteDirectory(root, copy);
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, dir.fullPath, file.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-123
+// Parameters: originFilePath = valid directory, destinationFilePath = valid directory, overwrite = true
+// Result: Test passes (replacing destination directory with a origin directory).
+function test_file_copyTo_123() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var dest = createDirForParent(root);
+    var child = createFileForParent(src);
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteDirectory(root, src);
+      deleteDirectory(root, dest);
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", (copy.fullPath == dest.fullPath) && isDir(copy));
+      TestEngine.test("resolve()", isFile(copy.resolve(child.name)));
+      deleteDirectory(root, copy);
+      deleteDirectory(root, src);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-124
+// Parameters: originFilePath = valid directory, destinationFilePath = valid directory, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_copyTo_error_124() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var dest = createDirForParent(root);
+    function on_copyTo_error(err) {
+     TestEngine.test("copyTo() [" + err.code + "]", (err.code == IO_ERR));
+     deleteDirectory(root, src);
+     deleteDirectory(root, dest);
+    }
+    function on_copyTo_success(copy) {
+     TestEngine.test("copyTo()", false);
+     deleteDirectory(root, copy);
+     deleteDirectory(root, src);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-125
+// Parameters: originFilePath = (empty) directory, overwrite = false
+// Result: Test passes.
+function test_file_moveTo_125() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var dest = root.fullPath + "/" + getDirName();
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", false);
+      deleteDirectory(root, src);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", isDir(result));
+      TestEngine.testPresetError(
+        "resolve() [NOT_FOUND_ERR]",
+        function() { root.resolve(src.name) },
+        NOT_FOUND_ERR
+      );
+      deleteDirectory(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-126
+// Parameters: originFilePath = (non-empty) directory, overwrite = false
+// Result: Test passes.
+function test_file_moveTo_126() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var file = createFileForParent(src);
+    var dest = root.fullPath + "/" + getDirName();
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", false);
+      deleteDirectory(root, src);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", isDir(result));
+      var child = result.resolve(file.name);
+      TestEngine.test("resolve()", isFile(child));
+      TestEngine.testPresetError(
+        "resolve() [NOT_FOUND_ERR]",
+        function() { root.resolve(src.name) },
+        NOT_FOUND_ERR
+      );
+      deleteDirectory(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-127
+// Parameters: originFilePath = undefined, other params = valid.
+// Result: INVALID_VALUES_ERR thrown via errorCallback.
+function test_file_moveTo_error_127() {
+  function on_resolve_success(root) {
+    var dest = root.fullPath + "/" + getDirName();
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo()", (err.code == INVALID_VALUES_ERR));
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, undefined, dest, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-128
+// Parameters: originFilePath = invalid path, overwrite = false
+// Result: INVALID_VALUES_ERR returned by error callback.
+function test_file_moveTo_error_128() {
+  function on_resolve_success(root) {
+    var src = "../";
+    var dest = root.fullPath + "/" + getDirName();
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src, dest, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-129
+// Parameters: originFilePath = valid file, destinationFilePath = valid directory, overwrite = true
+// Result: IO_ERR passed via error callback.
+function test_file_moveTo_129() {
+  function on_resolve_success(root) {
+    var src = createFileForParent(root);
+    var dest = createDirForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteFile(root, src);
+      deleteDirectory(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+      deleteFile(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-130
+// Parameters: originFilePath = valid file, destinationFilePath = valid directory, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_moveTo_error_130() {
+  function on_resolve_success(root) {
+    var src = createFileForParent(root);
+    var dest = createDirForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteFile(root, src);
+      deleteDirectory(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+      deleteFile(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-131
+// Parameters: originFilePath = valid directory, destinationFilePath = valid file, overwrite = true
+// Result: IO_ERR passed via error callback.
+function test_file_moveTo_131() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var child = createFileForParent(src);
+    var dest = createFileForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteDirectory(root, src);
+      deleteFile(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+      deleteFile(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-132
+// Parameters: originFilePath = valid directory, destinationFilePath = valid file, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_moveTo_error_132() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var child = createFileForParent(src);
+    var dest = createFileForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteDirectory(root, src);
+      deleteFile(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+      deleteDirectory(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-133
+// Parameters: originFilePath = valid directory, destinationFilePath = valid directory, overwrite = true
+// Result: Test passes (replacing destination directory with a origin directory).
+function test_file_moveTo_133() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var child = createFileForParent(src);
+    var dest = createDirForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", false);
+      deleteDirectory(root, src);
+      deleteDirectory(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", (result.fullPath == dest.fullPath) && isDir(result));
+      TestEngine.test("resolve()", isFile(result.resolve(child.name)));
+      TestEngine.testPresetError(
+        "resolve() [NOT_FOUND_ERR]",
+        function() { root.resolve(src.name); },
+        NOT_FOUND_ERR
+      );
+      deleteDirectory(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-134
+// Parameters: originFilePath = valid directory, destinationFilePath = valid directory, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_moveTo_error_134() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var child = createFileForParent(src);
+    var dest = createDirForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteDirectory(root, src);
+      deleteDirectory(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+      deleteDirectory(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-135
+// Parameters: filePath = valid path to an existing file
+// Result: Test passes.
+function test_file_resolve_135() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    var resolved = root.resolve(file.name);
+    TestEngine.test("resolve()", isFile(resolved) && (file.fullPath == resolved.fullPath));
+    deleteFile(root, file);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-136
+// Parameters: filePath = valid path to non-existing file
+// Result: NOT_FOUND_ERR thrown in place.
+function test_file_resolve_error_136() {
+  function on_resolve_success(root) {
+    var fileNotExist = getFileName();
+    TestEngine.testPresetError(
+      "resolve() [NOT_FOUND_ERR]",
+      function() { root.resolve(fileNotExist); },
+      NOT_FOUND_ERR
+    );
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-137
+// Parameters: filePath = invalid path
+// Result: NOT_FOUND_ERR thrown in place.
+function test_file_resolve_error_137() {
+  function on_resolve_success(root) {
+   var invalidPath = "../";
+   TestEngine.testPresetError(
+     "resolve() [INVALID_VALUES_ERR]",
+     function() { root.resolve(invalidPath); },
+     INVALID_VALUES_ERR
+   );
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-138: Open file in append mode and test append mode.
+function test_file_append_behaviour_138() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    function on_openStream_success(stream) {
+      function on_openStream_success2(stream) {
+        function on_openStream_success3(stream) {
+            var array = stream.readBytes(4);
+            TestEngine.test("readBytes(4)", array.length === 4);
+            TestEngine.test("array[0]", array[0] === 1);
+            TestEngine.test("array[1]", array[1] === 2);
+            TestEngine.test("array[2]", array[2] === 3);
+            TestEngine.test("array[3]", array[3] === 4);
+            stream.close();
+            deleteFile(file, file2);
+        }
+        TestEngine.test("openStream()", isFilestream(stream));
+        stream.writeBytes([3, 4]);
+        stream.close();
+        //reopen in read mode
+        var cb = TestEngine.registerCallback("openStream", on_openStream_success3, on_openStream_error);
+        file2.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+      }
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBytes([1, 2]);
+      stream.close();
+      //reopen again in append mode
+      var cb = TestEngine.registerCallback("openStream", on_openStream_success2, on_openStream_error);
+      file2.openStream(cb.successCallback, cb.errorCallback, "a", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file2.openStream(cb.successCallback, cb.errorCallback, "a", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-139: Set postion.
+function test_file_set_position_139() {
+  function on_resolve_error(err) {
+      TestEngine.test("resolve() [" + err.code + "]", false);
+  }
+  function on_resolve_success(file) {
+    function on_openStream_success(stream) {
+      function on_openStream_success2(stream) {
+        TestEngine.test("Correct postion after opening",
+            stream.position === 0);
+        var array = stream.readBytes(5);
+        TestEngine.test("Correct number of bytes read", array.length === 4);
+        TestEngine.test("Correct values of bytes read", array[0] === 5 &&
+            array[1] === 6 && array[2] === 7 && array[3] === 8);
+        stream.position = 2;
+        array = stream.readBytes(1);
+        TestEngine.test("Correct values of bytes read at pos 2",
+            array.length === 1 && array[0] === 7);
+        stream.position = 1;
+        array = stream.readBytes(1);
+        TestEngine.test("Correct values of bytes read at pos 1",
+            array.length === 1 && array[0] === 6);
+        stream.position = 0;
+        array = stream.readBytes(1);
+        TestEngine.test("Correct values of bytes read at pos 0",
+            array.length === 1 && array[0] === 5);
+        stream.position = 3;
+        array = stream.readBytes(1);
+        TestEngine.test("Correct values of bytes read at pos 3",
+            array.length === 1 && array[0] === 8);
+        stream.close();
+        deleteFile(file, file2);
+      }
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.test("Correct postion after opening",
+          stream.position === 0);
+      stream.writeBytes([1, 2, 3, 4]);
+      TestEngine.test("Correct postion after write ", stream.position === 4);
+      stream.position = 0;
+      TestEngine.test("Correct postion after setting postion",
+          stream.position === 0);
+      stream.writeBytes([5, 6, 7, 8]);
+      stream.close();
+      var cb = TestEngine.registerCallback("openStream",
+          on_openStream_success2, on_openStream_error);
+      file2.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    var cb = TestEngine.registerCallback("openStream",
+        on_openStream_success, on_openStream_error);
+    file2.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC2-FILESYSTEM-140: Resolve wgt-package in rw mode.
+// Result: UNKNOWN_ERR thrown via error callback.
+function test_filesystem_resolve_error_140() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", (err.code == UNKNOWN_ERR)); }
+  function on_resolve_success(file) { TestEngine.test("resolve()", false);}
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, 'wgt-package', 'rw');
+}
+
+// WAC2-FILESYSTEM-141: Resolve wgt-package/config.xml in rw mode.
+// Result: UNKNOWN_ERR thrown via error callback.
+function test_filesystem_resolve_error_141() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", (err.code == UNKNOWN_ERR)); }
+  function on_resolve_success(file) { TestEngine.test("resolve()", false);}
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, 'wgt-package/config.xml', 'rw');
+}
+
+// WAC2-FILESYSTEM-142: Resolve wgt-package in r mode.
+// Result: Success.
+function test_filesystem_resolve_142() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) { TestEngine.test("resolve()", isFileObject(file));}
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, 'wgt-package', 'r');
+}
+// WAC2-FILESYSTEM-143: Resolve wgt-package/config.xml in r mode.
+// Result: Success.
+function test_filesystem_resolve_143() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) { TestEngine.test("resolve()", isFileObject(file));}
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, 'wgt-package/config.xml', 'r');
+}
+
+//=============================================================================
+TestEngine.setTestSuiteName("[WAC2.0][Filesystem]");
+//TestEngine.addTest(true, test_filesystem_properties_001, "WAC-FILESYSTEM-001");
+//TestEngine.addTest(true, test_filesystem_resolve_002, "WAC-FILESYSTEM-002");
+//TestEngine.addTest(true, test_filesystem_resolve_003, "WAC-FILESYSTEM-003");
+//TestEngine.addTest(true, test_file_listFiles_004, "WAC-FILESYSTEM-004");
+//TestEngine.addTest(true, test_file_open_005, "WAC-FILESYSTEM-005");
+//TestEngine.addTest(true, test_file_open_006, "WAC-FILESYSTEM-006");
+//TestEngine.addTest(true, test_file_open_007, "WAC-FILESYSTEM-007");
+//TestEngine.addTest(true, test_file_open_error_008, "WAC-FILESYSTEM-008");
+//TestEngine.addTest(true, test_file_open_error_009, "WAC-FILESYSTEM-009");
+//TestEngine.addTest(true, test_file_copyTo_010, "WAC-FILESYSTEM-010");
+//TestEngine.addTest(true, test_file_copyTo_error_011, "WAC-FILESYSTEM-011");
+//TestEngine.addTest(true, test_file_copyTo_012, "WAC-FILESYSTEM-012");
+//TestEngine.addTest(true, test_file_createFile_013, "WAC-FILESYSTEM-013");
+//TestEngine.addTest(true, test_file_createFile_error_014, "WAC-FILESYSTEM-014");
+//TestEngine.addTest(true, test_file_createFile_error_015, "WAC-FILESYSTEM-015");
+//TestEngine.addTest(true, test_file_createFile_error_016, "WAC-FILESYSTEM-016");
+//TestEngine.addTest(true, test_file_createFile_error_017, "WAC-FILESYSTEM-017");
+//TestEngine.addTest(true, test_file_createDirectory_018, "WAC-FILESYSTEM-018");
+//TestEngine.addTest(true, test_file_createDirectory_error_019, "WAC-FILESYSTEM-019");
+//TestEngine.addTest(true, test_file_createDirectory_error_020, "WAC-FILESYSTEM-020");
+//TestEngine.addTest(true, test_file_createDirectory_error_021, "WAC-FILESYSTEM-021");
+//TestEngine.addTest(true, test_file_createDirectory_error_022, "WAC-FILESYSTEM-022");
+//TestEngine.addTest(true, test_file_moveTo_023, "WAC-FILESYSTEM-023");
+//TestEngine.addTest(true, test_file_moveTo_error_024, "WAC-FILESYSTEM-024");
+//TestEngine.addTest(true, test_file_moveTo_025, "WAC-FILESYSTEM-025");
+//TestEngine.addTest(true, test_file_deleteFile_026, "WAC-FILESYSTEM-026");
+//TestEngine.addTest(true, test_file_deleteFile_error_027, "WAC-FILESYSTEM-027");
+//TestEngine.addTest(true, test_file_deleteFile_error_028, "WAC-FILESYSTEM-028");
+//TestEngine.addTest(true, test_file_deleteFile_error_029, "WAC-FILESYSTEM-029");
+//TestEngine.addTest(true, test_file_deleteFile_error_030, "WAC-FILESYSTEM-030");
+//TestEngine.addTest(true, test_file_deleteDirectory_031, "WAC-FILESYSTEM-031");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_032, "WAC-FILESYSTEM-032");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_033, "WAC-FILESYSTEM-033");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_034, "WAC-FILESYSTEM-034");
+//TestEngine.addTest(true, test_filestream_write_read_035, "WAC-FILESYSTEM-035");
+TestEngine.addTest(true, test_filestream_read_error_036, "WAC-FILESYSTEM-036");
+//TestEngine.addTest(true, test_filestream_read_error_037, "WAC-FILESYSTEM-037");
+//TestEngine.addTest(true, test_file_open_error_038, "WAC-FILESYSTEM-038");
+//TestEngine.addTest(true, test_filestream_read_error_040, "WAC-FILESYSTEM-040");
+//TestEngine.addTest(true, test_filestream_write_error_041, "WAC-FILESYSTEM-041");
+//TestEngine.addTest(true, test_filestream_write_error_042, "WAC-FILESYSTEM-042");
+//TestEngine.addTest(true, test_filestream_write_error_043, "WAC-FILESYSTEM-043");
+//TestEngine.addTest(true, test_filestream_write_error_044, "WAC-FILESYSTEM-044");
+//TestEngine.addTest(true, test_filestream_read_error_045, "WAC-FILESYSTEM-045");
+//TestEngine.addTest(true, test_filestream_read_error_046, "WAC-FILESYSTEM-046");
+//TestEngine.addTest(true, test_filestream_writeBytes_readBytes_047, "WAC-FILESYSTEM-047");
+//TestEngine.addTest(true, test_filestream_readBytes_error_048, "WAC-FILESYSTEM-048");
+//TestEngine.addTest(true, test_filestream_readBytes_error_049, "WAC-FILESYSTEM-049");
+//TestEngine.addTest(true, test_filestream_readBytes_error_051, "WAC-FILESYSTEM-051");
+//TestEngine.addTest(true, test_filestream_readBytes_error_052, "WAC-FILESYSTEM-052");
+//TestEngine.addTest(true, test_filestream_readBytes_error_053, "WAC-FILESYSTEM-053");
+//TestEngine.addTest(true, test_filestream_writeBytes_error_054, "WAC-FILESYSTEM-054");
+//TestEngine.addTest(true, test_filestream_writeBytes_error_055, "WAC-FILESYSTEM-055");
+//TestEngine.addTest(true, test_filestream_writeBytes_error_056, "WAC-FILESYSTEM-056");
+//TestEngine.addTest(true, test_filestream_writeBytes_057, "WAC-FILESYSTEM-057");
+//TestEngine.addTest(true, test_filestream_writeBase64_readBase64_058, "WAC-FILESYSTEM-058");
+//TestEngine.addTest(true, test_filestream_writeBase64_read_059, "WAC-FILESYSTEM-059");
+//TestEngine.addTest(true, test_filestream_write_readBase64_060, "WAC-FILESYSTEM-060");
+//TestEngine.addTest(true, test_filestream_readBase64_error_061, "WAC-FILESYSTEM-061");
+//TestEngine.addTest(true, test_filestream_readBase64_error_062, "WAC-FILESYSTEM-062");
+//TestEngine.addTest(true, test_filestream_readBase64_error_064, "WAC-FILESYSTEM-064");
+//TestEngine.addTest(true, test_filestream_readBase64_error_065, "WAC-FILESYSTEM-065");
+//TestEngine.addTest(true, test_filestream_readBase64_error_066, "WAC-FILESYSTEM-066");
+//TestEngine.addTest(true, test_filestream_writeBase64_error_067, "WAC-FILESYSTEM-067");
+//TestEngine.addTest(true, test_filestream_writeBase64_error_068, "WAC-FILESYSTEM-068");
+//TestEngine.addTest(true, test_filestream_writeBase64_error_069, "WAC-FILESYSTEM-069");
+//TestEngine.addTest(true, test_filestream_writeBase64_error_070, "WAC-FILESYSTEM-070");
+//TestEngine.addTest(true, test_file_createFile_error_071, "WAC-FILESYSTEM-071");
+//TestEngine.addTest(true, test_file_deleteFile_error_072, "WAC-FILESYSTEM-072");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_073, "WAC-FILESYSTEM-073");
+//TestEngine.addTest(true, test_file_moveTo_error_074, "WAC-FILESYSTEM-074");
+//TestEngine.addTest(true, test_file_openStream_error_075, "WAC-FILESYSTEM-075");
+//TestEngine.addTest(true, test_file_readAsText_076, "WAC-FILESYSTEM-076");
+//TestEngine.addTest(true, test_file_readAsText_error_077, "WAC-FILESYSTEM-077");
+//TestEngine.addTest(true, test_file_readAsText_error_078, "WAC-FILESYSTEM-078");
+//TestEngine.addTest(true, test_file_toUri_079, "WAC-FILESYSTEM-079");
+//TestEngine.addTest(true, test_filesystem_resolve_080, "WAC-FILESYSTEM-080");
+//TestEngine.addTest(true, test_file_listFiles_081, "WAC-FILESYSTEM-081");
+//TestEngine.addTest(true, test_file_listFiles_082, "WAC-FILESYSTEM-082");
+//TestEngine.addTest(true, test_file_listFiles_error_083, "WAC-FILESYSTEM-083");
+//TestEngine.addTest(true, test_file_listFiles_error_084, "WAC-FILESYSTEM-084");
+//TestEngine.addTest(true, test_file_listFiles_error_085, "WAC-FILESYSTEM-085");
+//TestEngine.addTest(true, test_file_listFiles_error_086, "WAC-FILESYSTEM-086");
+//TestEngine.addTest(true, test_file_open_087, "WAC-FILESYSTEM-087");
+//TestEngine.addTest(true, test_file_open_error_088, "WAC-FILESYSTEM-088");
+//TestEngine.addTest(true, test_file_open_error_089, "WAC-FILESYSTEM-089");
+//TestEngine.addTest(true, test_file_open_error_090, "WAC-FILESYSTEM-090");
+//TestEngine.addTest(true, test_file_readAsText_091, "WAC-FILESYSTEM-091");
+//TestEngine.addTest(true, test_file_readAsText_092, "WAC-FILESYSTEM-092");
+//TestEngine.addTest(true, test_file_readAsText_093, "WAC-FILESYSTEM-093");
+//TestEngine.addTest(true, test_file_readAsText_094, "WAC-FILESYSTEM-094");
+//TestEngine.addTest(true, test_file_readAsText_error_095, "WAC-FILESYSTEM-095");
+//TestEngine.addTest(true, test_file_readAsText_error_096, "WAC-FILESYSTEM-096");
+//TestEngine.addTest(true, test_file_readAsText_error_097, "WAC-FILESYSTEM-097");
+//TestEngine.addTest(true, test_file_readAsText_error_098, "WAC-FILESYSTEM-098");
+//TestEngine.addTest(true, test_file_deleteDirectory_099, "WAC-FILESYSTEM-099");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_100, "WAC-FILESYSTEM-100");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_101, "WAC-FILESYSTEM-101");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_102, "WAC-FILESYSTEM-102");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_103, "WAC-FILESYSTEM-103");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_104, "WAC-FILESYSTEM-104");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_105, "WAC-FILESYSTEM-105");
+//TestEngine.addTest(true, test_file_deleteFile_106, "WAC-FILESYSTEM-106");
+//TestEngine.addTest(true, test_file_deleteFile_error_107, "WAC-FILESYSTEM-107");
+//TestEngine.addTest(true, test_file_deleteFile_error_108, "WAC-FILESYSTEM-108");
+//TestEngine.addTest(true, test_file_deleteFile_error_109, "WAC-FILESYSTEM-109");
+//TestEngine.addTest(true, test_file_deleteFile_error_110, "WAC-FILESYSTEM-110");
+//TestEngine.addTest(true, test_file_deleteFile_error_111, "WAC-FILESYSTEM-111");
+//TestEngine.addTest(true, test_filesystem_resolve_112, "WAC-FILESYSTEM-112");
+//TestEngine.addTest(true, test_file_readAsText_113, "WAC-FILESYSTEM-113");
+//TestEngine.addTest(true, test_file_open_114, "WAC-FILESYSTEM-114");
+//TestEngine.addTest(true, test_file_copyTo_115, "WAC-FILESYSTEM-115");
+//TestEngine.addTest(true, test_file_copyTo_116, "WAC-FILESYSTEM-116");
+//TestEngine.addTest(true, test_file_copyTo_error_117, "WAC-FILESYSTEM-117");
+//TestEngine.addTest(true, test_file_copyTo_error_118, "WAC-FILESYSTEM-118");
+//TestEngine.addTest(true, test_file_copyTo_119, "WAC-FILESYSTEM-119");
+//TestEngine.addTest(true, test_file_copyTo_error_120, "WAC-FILESYSTEM-120");
+//TestEngine.addTest(true, test_file_copyTo_121, "WAC-FILESYSTEM-121");
+//TestEngine.addTest(true, test_file_copyTo_error_122, "WAC-FILESYSTEM-122");
+//TestEngine.addTest(true, test_file_copyTo_123, "WAC-FILESYSTEM-123");
+//TestEngine.addTest(true, test_file_copyTo_error_124, "WAC-FILESYSTEM-124");
+//TestEngine.addTest(true, test_file_moveTo_125, "WAC-FILESYSTEM-125");
+//TestEngine.addTest(true, test_file_moveTo_126, "WAC-FILESYSTEM-126");
+//TestEngine.addTest(true, test_file_moveTo_error_127, "WAC-FILESYSTEM-127");
+//TestEngine.addTest(true, test_file_moveTo_error_128, "WAC-FILESYSTEM-128");
+//TestEngine.addTest(true, test_file_moveTo_129, "WAC-FILESYSTEM-129");
+//TestEngine.addTest(true, test_file_moveTo_error_130, "WAC-FILESYSTEM-130");
+//TestEngine.addTest(true, test_file_moveTo_131, "WAC-FILESYSTEM-131");
+//TestEngine.addTest(true, test_file_moveTo_error_132, "WAC-FILESYSTEM-132");
+//TestEngine.addTest(true, test_file_moveTo_133, "WAC-FILESYSTEM-133");
+//TestEngine.addTest(true, test_file_moveTo_error_134, "WAC-FILESYSTEM-134");
+//TestEngine.addTest(true, test_file_resolve_135, "WAC-FILESYSTEM-135");
+//TestEngine.addTest(true, test_file_resolve_error_136, "WAC-FILESYSTEM-136");
+//TestEngine.addTest(true, test_file_resolve_error_137, "WAC-FILESYSTEM-137");
+//TestEngine.addTest(true, test_file_append_behaviour_138, "WAC-FILESYSTEM-138");
+//TestEngine.addTest(true, test_file_set_position_139, "WAC-FILESYSTEM-139");
+//TestEngine.addTest(true, test_filesystem_resolve_error_140, "WAC-FILESYSTEM-140");
+//TestEngine.addTest(true, test_filesystem_resolve_error_141, "WAC-FILESYSTEM-141");
+//TestEngine.addTest(true, test_filesystem_resolve_142, "WAC-FILESYSTEM-142");
+//TestEngine.addTest(true, test_filesystem_resolve_143, "WAC-FILESYSTEM-143");
+
+//=============================================================================
+// --------------------------| Utilities
+
+function isFileObject(obj) {
+  return (obj instanceof deviceapis.filesystem.File);
+}
+
+function isFile(obj) {
+  return (isFileObject(obj) && !obj.isDirectory);
+}
+
+function isDir(obj) {
+  return (isFileObject(obj) && obj.isDirectory);
+}
+
+function isFilestream(obj) {
+  return (obj instanceof deviceapis.filesystem.FileStream);
+}
+
+function deleteDirectory(parent, dir) {
+  function on_error(err) {
+    TestEngine.test("deleteDirectory() [" + err.code + "]", false);
+  }
+  function on_success() {
+    TestEngine.test("deleteDirectory()", true);
+  }
+  var cb = TestEngine.registerCallback("deleteDirectory", on_success, on_error);
+  parent.deleteDirectory(cb.successCallback, cb.errorCallback, dir.fullPath, true);
+}
+
+function deleteFile(parent, file) {
+  function on_error(err) {
+    TestEngine.test("deleteFile() [" + err.code + "]", false);
+  }
+  function on_success() {
+    TestEngine.test("deleteFile()", true);
+  }
+  var cb = TestEngine.registerCallback("deleteFile", on_success, on_error);
+  parent.deleteFile(cb.successCallback, cb.errorCallback, file.fullPath);
+}
+
+// For common behaviour use resolve_root_location
+function resolve_root(on_success_callback, on_error_callback) {
+  var cb = TestEngine.registerCallback("resolve", on_success_callback, on_error_callback);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION);
+}
+
+function resolve_root_location(handler) {
+  function on_resolve_error(err) {
+    TestEngine.test("resolve() [" + err.code + "]", false);
+  }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    handler(file);
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION);
+}
+
+var counter = 1;
+
+function getFileName() {
+  var nr = Math.floor(Math.random() * 1000);
+  var date = new Date();
+  return "test_wac20_filesystem_file_" + nr + "_" + (counter++) + "_"
+         + date.getMinutes() + date.getSeconds() + date.getMilliseconds();
+}
+
+function getDirName() {
+  var nr = Math.floor(Math.random() * 1000);
+  var date = new Date();
+  return "test_wac20_filesystem_dir_" + nr + "_" + (counter++) + "_"
+         + date.getMinutes() + date.getSeconds() + date.getMilliseconds();
+}
+
+function createFileForParent(parent) {
+  var result = parent.createFile(getFileName());
+  TestEngine.test("createFile()", isFile(result));
+  return result;
+}
+
+function createDirForParent(parent) {
+  var result = parent.createDirectory(getDirName());
+  TestEngine.test("createDirectory()", isDir(result));
+  return result;
+}
+
+function testNoExceptionWithMessage(message, fun) {
+  var testResult = true;
+  try {
+    fun();
+  }
+  catch (e) {
+    testResult = false;
+  }
+  TestEngine.test(message, testResult);
+}
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestGeolocation.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestGeolocation.js
new file mode 100644 (file)
index 0000000..418ef3e
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+function presenceTest()
+{
+    TestEngine.test("Checking checking", true);
+    TestEngine.test("Checking Geolocation object", navigator.geolocation);
+
+    TestEngine.test("Checking function getCurrentPosition",
+        isFunction(navigator.geolocation.getCurrentPosition));
+}
+
+function accessTest()
+{
+    try {
+        jsPrint("DEBUG POINT 0");
+        var callbackObject = TestEngine.registerCallback("getCurrentPositionCallback",
+                                                         localSuccessCallback,
+                                                         localErrorCallback);
+        jsPrint("DEBUG POINT 1");
+        navigator.geolocation.getCurrentPosition(
+            callbackObject.successCallback,
+            callbackObject.errorCallback);
+        jsPrint("DEBUG POINT 2");
+    } catch (error) {
+        jsPrint("DEBUG POINT 3");
+        TestEngine.logErr("Error in: navigator.geolocation.getCurrentPosition");
+    }
+    jsPrint("DEBUG POINT 4");
+}
+
+TestEngine.setTestSuiteName("[WAC2.0][Geolocation]", 30*1000); // 30 seconds
+TestEngine.addTest(true, presenceTest, "[WAC2.0][Geolocation] Geolocation prenence test");
+TestEngine.addTest(true, accessTest, "[WAC2.0][Geolocation] Access test");
+TestEngine.setFinalCallback(function(){ jsPrint("closing window"); window.close(); });
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestMessaging.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestMessaging.js
new file mode 100644 (file)
index 0000000..5fb175e
--- /dev/null
@@ -0,0 +1,1242 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test contact class.
+ *
+ * @author      Lukasz Marek (l.marek@samsung.com)
+ * @version     0.1
+ */
+
+
+var MsgObj = deviceapis.messaging;
+var FsObj = deviceapis.filesystem;
+var destinationPhoneNumbers = ["+48784619935", "+48784619935"];
+var destinationEmails = ["ibisz.krzys@gmail.com"];
+var filename1 = "Attachment1.txt"
+var filename2 = "Attachment2.txt"
+var filename3 = "Attachment3.txt"
+var file1 = null
+var file2 = null
+var file3 = null
+var imageDir = null;
+var currentDate = new Date();
+var defaultBody = "first message%\\ " + currentDate;
+var changedBody = "changed body";
+var INVALID_VALUES_ERR = 22;
+var TYPE_MISMATCH_ERR = 17;
+
+// msg001
+function presenceTest()
+{
+    TestEngine.test("Checking checking", true);
+    TestEngine.test("Checking deviceapis object", deviceapis);
+    TestEngine.test("Checking messaging object", MsgObj);
+    TestEngine.test("Checking filesystem object", FsObj);
+
+    TestEngine.test("Checking type of createMessage", isFunction(MsgObj.createMessage));
+    TestEngine.test("Checking type of sendMessage", isFunction(MsgObj.sendMessage));
+    TestEngine.test("Checking type of findMessages", isFunction(MsgObj.findMessages));
+    TestEngine.test("Checking type of onSMS", isFunction(MsgObj.onSMS));
+    TestEngine.test("Checking type of onMMS", isFunction(MsgObj.onMMS));
+    TestEngine.test("Checking type of onEmail", isFunction(MsgObj.onEmail));
+    TestEngine.test("Checking type of unsubscribe", isFunction(MsgObj.unsubscribe));
+
+    TestEngine.test("Checking type and value of TYPE_SMS", MsgObj.TYPE_SMS === 1);
+    TestEngine.test("Checking type and value of TYPE_MMS", MsgObj.TYPE_MMS === 2);
+    TestEngine.test("Checking type and value of TYPE_EMAIL", MsgObj.TYPE_EMAIL === 3);
+    MsgObj.TYPE_SMS = 66;
+    MsgObj.TYPE_MMS = 66;
+    MsgObj.TYPE_EMAIL = 66;
+    TestEngine.test("Checking read only of TYPE_SMS", MsgObj.TYPE_SMS === 1);
+    TestEngine.test("Checking read only of TYPE_MMS", MsgObj.TYPE_MMS === 2);
+    TestEngine.test("Checking read only of TYPE_EMAIL", MsgObj.TYPE_EMAIL === 3);
+
+    TestEngine.test("Checking type and value of FOLDER_INBOX", MsgObj.FOLDER_INBOX === 1);
+    TestEngine.test("Checking type and value of FOLDER_OUTBOX", MsgObj.FOLDER_OUTBOX === 2);
+    TestEngine.test("Checking type and value of FOLDER_DRAFTS", MsgObj.FOLDER_DRAFTS === 3);
+    TestEngine.test("Checking type and value of FOLDER_SENTBOX", MsgObj.FOLDER_SENTBOX === 4);
+    MsgObj.FOLDER_INBOX = 66;
+    MsgObj.FOLDER_OUTBOX = 66;
+    MsgObj.FOLDER_DRAFTS = 66;
+    MsgObj.FOLDER_SENTBOX = 66;
+    TestEngine.test("Checking type and value of FOLDER_INBOX", MsgObj.FOLDER_INBOX === 1);
+    TestEngine.test("Checking type and value of FOLDER_OUTBOX", MsgObj.FOLDER_OUTBOX === 2);
+    TestEngine.test("Checking type and value of FOLDER_DRAFTS", MsgObj.FOLDER_DRAFTS === 3);
+    TestEngine.test("Checking type and value of FOLDER_SENTBOX", MsgObj.FOLDER_SENTBOX === 4);
+}
+
+// msg002
+function createMessageInvalidParamsTest()
+{
+    TestEngine.catchErrorType("code", INVALID_VALUES_ERR, MsgObj, "createMessage", undefined);
+    TestEngine.catchErrorType("code", INVALID_VALUES_ERR, MsgObj, "createMessage", null);
+    TestEngine.catchErrorType("code", INVALID_VALUES_ERR, MsgObj, "createMessage", "test");
+    TestEngine.catchErrorType("code", INVALID_VALUES_ERR, MsgObj, "createMessage", new Date());
+    TestEngine.catchErrorType("code", INVALID_VALUES_ERR, MsgObj, "createMessage", [6, 6, 6]);
+}
+
+// msg003
+function createMMSTest()
+{
+    createMessageCheck(MsgObj.TYPE_MMS);
+}
+
+// msg004
+function createSMSTest()
+{
+    createMessageCheck(MsgObj.TYPE_SMS);
+}
+
+// msg005
+function createEmailTest()
+{
+    createMessageCheck(MsgObj.TYPE_EMAIL);
+}
+
+function createMessageCheck(type)
+{
+    var msg = MsgObj.createMessage(type);
+    TestEngine.test("message object created", typeof(msg) == 'object');
+    if (typeof(msg) == 'object') {
+
+        var props = new Array();
+        props.push(new Array('id',null,"999",true,TestEngine.STRING));
+        props.push(new Array('type',MsgObj.type,999,false,TestEngine.NUMBER));
+        props.push(new Array('folder',undefined,999,false,undefined));
+        props.push(new Array('timestamp',null,new Date(2010,12,17),true,TestEngine.DATE));
+
+        // email only
+        if(type === MsgObj.TYPE_EMAIL) {
+            props.push(new Array('from',null,"maupa@samsung.com",true,TestEngine.STRING));
+            props.push(new Array('cc',null,null,false));
+            TestEngine.test("length of cc attribute", msg.cc.length === 0);
+            props.push(new Array('bcc',null,null,false));
+            TestEngine.test("length of bcc attribute", msg.bcc.length === 0);
+            props.push(new Array('priority',null,true,false,TestEngine.BOOL));
+        }
+
+        props.push(new Array('to',null,null,false));
+        props.push(new Array('body',null,"test",false,TestEngine.STRING));
+        props.push(new Array('isRead',null,true,false,TestEngine.BOOL));
+
+        // MMS and email only
+        if(type === MsgObj.TYPE_EMAIL || type == MsgObj.TYPE_MMS) {
+            props.push(new Array('subject',null,"subject",false,TestEngine.STRING));
+            props.push(new Array('attachments'));
+            TestEngine.test("length of attachments attribute", msg.attachments.length === 0);
+        }
+
+        props.push(new Array('update',null,null,false,TestEngine.FUNCTION));
+        TestEngine.testProperties(msg, props);
+
+        TestEngine.test("length of to attribute", msg.to.length === 0);
+    }
+}
+
+// msg006
+function sendMessageInvalidParamsTest()
+{
+    function messageSent() {
+        TestEngine.test("The SMS has been sent", false);
+    }
+    function messageFailed(error) {
+        TestEngine.test("The SMS could not be sent " + error.message, true);
+    }
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage");
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent);
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed);
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, undefined);
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, null);
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, 66);
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, "test");
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, new Date());
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, [6, 6, 6]);
+
+    var msg = MsgObj.createMessage(MsgObj.TYPE_SMS);
+    msg.body = "Message sent by test unit sendMessageInvalidParamsTest()";
+    msg.subject = "Subject of message";
+    msg.to = destinationPhoneNumbers;
+    var cbObj = TestEngine.registerCallback("sendMessage", null, messageFailed);
+    MsgObj.sendMessage(null, cbObj.errorCallback, msg);
+}
+
+function sendMMSTestSuccess()
+{
+    TestEngine.test("callback: MMS is sent", true);
+}
+
+function sendMMSTestFail()
+{
+    TestEngine.test("callback: MMS is sent", false);
+}
+
+// msg007
+function sendMMSTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_MMS);
+    if (typeof(msg) == 'object') {
+        TestEngine.test("MMS is created", true);
+        msg.body = "Message sent by test unit sendMMSTest()";
+        msg.subject = "Subject of message";
+        msg.to = destinationPhoneNumbers;
+        //some attachments?
+        var cbObj = TestEngine.registerCallback("sendMMSTest", sendMMSTestSuccess, sendMMSTestFail);
+        MsgObj.sendMessage(cbObj.successCallback, cbObj.errorCallback, msg);
+    }
+    else {
+        TestEngine.test("MMS is created", false);
+    }
+}
+
+function sendSMSTestSuccess()
+{
+    TestEngine.test("callback: SMS is sent", true);
+}
+
+function sendSMSTestFail()
+{
+    TestEngine.test("callback: SMS is sent", false);
+}
+
+// msg008
+function sendSMSTest()
+{
+    var msg1 = MsgObj.createMessage(MsgObj.TYPE_SMS);
+    if (typeof(msg1) == 'object') {
+        TestEngine.test("SMS is created", true);
+
+        msg1.body = "Message 1 sent by test unit sendSMSTest()";
+        msg1.to = destinationPhoneNumbers;
+        var cbObj1 = TestEngine.registerCallback("sendSMSTest1", sendSMSTestSuccess, sendSMSTestFail);
+        MsgObj.sendMessage(cbObj1.successCallback, cbObj1.errorCallback, msg1);
+    }
+    else {
+        TestEngine.test("SMS is created", false);
+    }
+}
+
+function sendEmailTestSuccess()
+{
+    TestEngine.test("callback: Email is sent", true);
+}
+
+function sendEmailTestFail()
+{
+    TestEngine.test("callback: Email is not sent", false);
+}
+
+// msg009
+function sendEmailTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+    if (typeof(msg) == 'object') {
+        TestEngine.test("Email is created", true);
+        msg.body = "Message sent by test unit sendEmailTest()";
+        msg.subject = "[WIDGET SPAM]Subject of message";
+        msg.to = destinationEmails;
+        //some attachments?
+        var cbObj = TestEngine.registerCallback("sendEmailTest", sendEmailTestSuccess, sendEmailTestFail);
+        MsgObj.sendMessage(cbObj.successCallback, cbObj.errorCallback, msg);
+    }
+    else {
+        TestEngine.test("Email is not created", false);
+    }
+}
+
+function findMessageTest(type)
+{
+    var addr1 = "+48123456789";
+    var addr2 = "+48607880564";
+    var addr3 = "+48111111111";
+    var addr4 = "+48999999999";
+    if(type === MsgObj.TYPE_EMAIL) {
+        addr1 = "aaa@bbb.com";
+        addr2 = "bbb@bbb.com";
+        addr3 = "ccc@bbb.com";
+        addr4 = "ddd@bbb.com";
+    }
+
+    var cases = new Array();
+    var currentCase = 0;
+    var newmsg;
+
+    // success callback
+    function successCallback_findMessages(messages)
+    {
+        TestEngine.logOK("SuccessCallback_findMessages enter, messages=" +messages+ ", msg count=" + messages.length);
+        TestEngine.test("Found more than 0 messages", messages.length > 0);
+
+        var matchFound = false;
+
+        // check results
+        for(var i in messages)
+        {
+            // compare types
+            if(messages[i].type === type) {
+                TestEngine.log("Comparing message (" + messages[i].id + ") type " + messages[i].type + " :OK");
+
+                // compare bodies
+                if(messages[i].body.indexOf(defaultBody) === 0) {
+                    TestEngine.log("Comparing message (" + messages[i].id + ") body " + messages[i].body + " :OK");
+                    matchFound = true;
+                    break;
+                }
+                else {
+                    TestEngine.log("Comparing message (" + messages[i].id + ") body " + messages[i].body + " :failed" );
+                }
+            }
+            else {
+                TestEngine.log("Comparing message (" + messages[i].id + ") type " + messages[i].type + " :failed" );
+            }
+        }
+
+        TestEngine.test("Match found" , matchFound);
+
+        currentCase++;
+        processNextCase();
+    }
+
+    // error callback
+    function errorCallback_findMessages(result)
+    {
+        TestEngine.test("errorCallback_findMessages enter, result.code=" + result.code, false);
+
+        currentCase++;
+        processNextCase();
+    }
+
+    // send success callback
+    function sendSucceeded() {
+        TestEngine.test("Test message successfully sent", true);
+
+        var msg;
+
+        //set up body filter
+        msg = { body:"first messa%", description:"Filter by body" };
+        cases.push(msg);
+
+        //set up subject filter
+        if(type != MsgObj.TYPE_SMS) {
+            msg = { subject:"%meaningless%", description:"Filter by subject" };
+            cases.push(msg);
+        }
+
+        //set up destination address filter
+        msg = { to:[addr1], description:"Filter by to" };
+        cases.push(msg);
+
+        //set up isRead filter
+        msg = { isRead:false, description:"Filter by isRead" };
+        cases.push(msg);
+
+        if (type === MsgObj.TYPE_EMAIL) {
+            //set up messagePriority filter
+            msg = { messagePriority:true, description:"Filter by messagePriority" };
+            cases.push(msg);
+
+            //set up cc filter
+            msg = { cc:[addr3], description:"Filter by cc" };
+            cases.push(msg);
+
+            //set up bcc filter
+            msg = { bcc:[addr4], description:"Filter by bcc" };
+            cases.push(msg);
+
+            //set up id filter
+            msg = { id:newmsg.id, description:"Filter by id" };
+            cases.push(msg);
+        }
+
+        //set up time filter
+        var start = new Date(2009,01);
+        var end = new Date(2015,01);
+        msg = { startTimestamp:start, endTimestamp:end, description:"Filter by dates" };
+        cases.push(msg);
+
+        //set up folder filter
+        msg = { folder:[MsgObj.FOLDER_SENTBOX], description:"Filter by folder" };
+        cases.push(msg);
+
+        //set up from filter
+        msg = { from:newmsg.from, description:"Filter by from" };
+        cases.push(msg);
+
+        //set up complex filter
+        msg = { body:"first messa%",
+                to:[addr1],
+                id:newmsg.id,
+                startTimestamp:start,
+                endTimestamp:end,
+                folder:[MsgObj.FOLDER_SENTBOX],
+                type:[type],
+                from:newmsg.from,
+                description:"complex filter"
+                };
+        if (type != MsgObj.TYPE_EMAIL) {
+            delete msg.id;
+        }
+
+        cases.push(msg);
+
+        // % (0 or more) and escape character. \\% - escaped '%', \\ - '\'
+        msg = { body:"%first %sage\\%\\ %", description:"Filter by body (% and escapes)" }
+        cases.push(msg);
+
+        // % (0 or more) in string array
+        if(type === MsgObj.TYPE_EMAIL) {
+            msg = { to:["%@bbb.%","%aa%"], description:"Filter by to (using %)" }     // EMAIL
+        }
+        else {
+            msg = { to:["%1234%","%45678%"], description:"Filter by to (using %)" }   // MMS & MMS
+        }
+        cases.push(msg);
+
+        processNextCase();
+    }
+
+    // send failure callback
+    function sendFailed() {
+        TestEngine.test("Test message sending failed", false);
+    }
+
+    // helper function
+    function processNextCase() {
+        if(currentCase < cases.length) {
+            TestEngine.log("");
+            TestEngine.log("Processing case " + currentCase);
+            TestEngine.log(cases[currentCase].description);
+            delete cases[currentCase].description;
+            var cObj = TestEngine.registerCallback("findMessages", successCallback_findMessages, errorCallback_findMessages)
+            MsgObj.findMessages(cObj.successCallback, cObj.errorCallback, cases[currentCase])
+        }
+    }
+
+    try {
+        //create message to be found
+        newmsg = MsgObj.createMessage(type);
+        newmsg.body = defaultBody;
+        newmsg.to = [addr1,addr2];
+        if(type === MsgObj.TYPE_EMAIL) {
+            newmsg.cc = [addr3];
+            newmsg.bcc = [addr4];
+            newmsg.priority = true;
+        }
+        if(type != MsgObj.SMS) {
+            newmsg.subject = "some meaningless subject";
+        }
+        var cb = TestEngine.registerCallback("sendMessage",sendSucceeded,sendFailed);
+        MsgObj.sendMessage(cb.successCallback,cb.errorCallback,newmsg);
+
+    } catch(e) {
+        TestEngine.logErr("findMessages exception: " + e.message);
+    }
+}
+
+function findNoMessageTest(type)
+{
+    var addr1 = "+48123456789";
+    var addr2 = "+48607880564";
+    var addr3 = "+48111111111";
+    var addr4 = "+48999999999";
+    if(type === MsgObj.TYPE_EMAIL)
+    {
+        addr1 = "aaa@bbb.com";
+        addr2 = "bbb@bbb.com";
+        addr3 = "ccc@bbb.com";
+        addr4 = "ddd@bbb.com";
+    }
+
+    var cases = new Array();
+    var currentCase = 0;
+    var newmsg;
+
+    // success callback
+    function successCallback_findMessages(messages)
+    {
+        TestEngine.logOK("successCallback_findMessages enter, messages=" +messages+ ", msg count=" + messages.length);
+        TestEngine.test("No messages should be found", messages.length == 0);
+
+        currentCase++;
+        processNextCase();
+    }
+
+    // error callback
+    function errorCallback_findMessages(result)
+    {
+        TestEngine.test("errorCallback_findMessages enter, result.code=" + result.code, false);
+
+        currentCase++;
+        processNextCase();
+    }
+
+    // send success callback
+    function sendSucceeded() {
+        TestEngine.test("Test message successfully sent", true);
+
+        //set up body filter
+        msg = { body:"first messaa%", id:newmsg.id };
+        cases.push(msg);
+
+        //set up subject filter
+        msg = { subject:"%meaningleess%", id:newmsg.id };
+        cases.push(msg);
+
+        //set up destination address filter
+        msg = { to:[addr3], id:newmsg.id };
+        cases.push(msg);
+
+        //set up isRead filter
+        msg = { isRead:true, id:newmsg.id };
+        cases.push(msg);
+
+        //set up messagePriority filter
+        msg = { messagePriority:false, id:newmsg.id };
+        cases.push(msg);
+
+        //set up id filter
+        msg = { id:newmsg.id + "0000" };
+        cases.push(msg);
+
+        //set up time filter
+        var start = new Date(2008,01);
+        var end = new Date(2010,01);
+        msg = { endTimestamp:end, id:newmsg.id };
+        cases.push(msg);
+
+        //set up folder filter
+        msg = { folder:[MsgObj.FOLDER_INBOX], id:newmsg.id };
+        cases.push(msg);
+
+        //set up from filter
+        msg = { from:"aaa@aaa.com", id:newmsg.id };
+        cases.push(msg);
+
+        //set up cc filter
+        msg = { cc:[addr1], id:newmsg.id };
+        cases.push(msg);
+
+        //set up bcc filter
+        msg = { bcc:[addr1], id:newmsg.id };
+        cases.push(msg);
+
+        // % (0 or more) and escape character
+        msg = { body:"%first mess%sage\%", id:newmsg.id }
+        cases.push(msg);
+
+        // % (0 or more) in string array
+        if(type === MsgObj.TYPE_EMAIL) {
+            msg = { to:["%c@bbb.%","%aa%"], id:newmsg.id }     // EMAIL
+        }
+        else {
+            msg = { to:["%12354%","%45678%"], id:newmsg.id }   // MMS & SMS
+        }
+        cases.push(msg);
+
+        processNextCase();
+    }
+
+    // send failure callback
+    function sendFailed() {
+        TestEngine.test("Test message sending failed", false);
+    }
+
+    // helper function
+    function processNextCase() {
+        if(currentCase < cases.length) {
+            TestEngine.log("");
+            TestEngine.log("Processing case " + currentCase);
+            var cObj = TestEngine.registerCallback("findMessages", successCallback_findMessages, errorCallback_findMessages)
+            MsgObj.findMessages(cObj.successCallback, cObj.errorCallback, cases[currentCase])
+        }
+    }
+
+    try {
+        //create message not to be found
+        newmsg = MsgObj.createMessage(type);
+        newmsg.body = "first message"
+        newmsg.to = [addr1,addr2];
+        if(type === MsgObj.TYPE_EMAIL) {
+            newmsg.cc = [addr3];
+            newmsg.bcc = [addr4];
+            newmsg.priority = true;
+        }
+        if(type != MsgObj.SMS) {
+            newmsg.subject = "some meaningless subject";
+        }
+        var cb = TestEngine.registerCallback("sendMessage",sendSucceeded,sendFailed);
+        MsgObj.sendMessage(cb.successCallback,cb.errorCallback,newmsg);
+
+    } catch(e) {
+        TestEngine.logErr("findMessages exception: " + e.message);
+    }
+}
+
+// msg013
+function findEmailTest()
+{
+    findMessageTest(MsgObj.TYPE_EMAIL)
+}
+
+// msg014
+function findSMSTest()
+{
+    findMessageTest(MsgObj.TYPE_SMS)
+}
+
+// msg015
+function findMMSTest()
+{
+    findMessageTest(MsgObj.TYPE_MMS)
+}
+
+// msg016
+function findNoEmailTest()
+{
+    findNoMessageTest(MsgObj.TYPE_EMAIL)
+}
+
+// msg017
+function findNoSMSTest()
+{
+    findNoMessageTest(MsgObj.TYPE_SMS)
+}
+
+// msg018
+function findNoMMSTest()
+{
+    findNoMessageTest(MsgObj.TYPE_MMS)
+}
+
+// msg019
+function findMessageInvalidParamsTest()
+{
+    function messageFound() {
+        TestEngine.test("The message has been found", false);
+    }
+    function messageFailed(error) {
+        TestEngine.test("The message could not be found " + error.message, true);
+    }
+
+    var cb = TestEngine.registerCallback("findMessages", null, messageFailed);
+    MsgObj.findMessages(null, cb.errorCallback);
+
+    var filter = { type:[MsgObj.TYPE_SMS], body:"aaa" };
+    var cb = TestEngine.registerCallback("findMessages", null, messageFailed);
+    MsgObj.findMessages(null, cb.errorCallback, filter);
+}
+
+// msg020
+function unsubscribeInvalidTest()
+{
+    invalidUnsubscribeCheck();
+
+    // If the subscriptionHandler argument does not correspond to a valid subscription, the method should return without any further action.
+    try
+    {
+        MsgObj.unsubscribe(123);
+        TestEngine.test("No error thrown from: messaging.unsubscribe", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function invalidUnsubscribeCheck()
+{
+    TestEngine.catchErrorType("code",17, MsgObj, "unsubscribe");
+}
+
+// msg021
+function onSMSInvalidTest()
+{
+    onIncomingMessageInvalidCheck("onSMS");
+}
+
+// msg022
+function onMMSInvalidTest()
+{
+    onIncomingMessageInvalidCheck("onMMS");
+}
+
+// msg023
+function onEmailInvalidTest()
+{
+    onIncomingMessageInvalidCheck("onEmail");
+}
+
+function onIncomingMessageInvalidCheck(func)
+{
+    // bad values
+    TestEngine.catchErrorType("code",17, MsgObj, func);
+    TestEngine.catchErrorType("code",17, MsgObj, func, null);
+    TestEngine.catchErrorType("code",17, MsgObj, func, undefined);
+    TestEngine.catchErrorType("code",17, MsgObj, func, -666);
+    TestEngine.catchErrorType("code",17, MsgObj, func, new Date());
+    TestEngine.catchErrorType("code",17, MsgObj, func, [6, 6, 6]);
+}
+
+// msg024
+function onSMSTest()
+{
+    onIncomingMessageCheck("onSMS");
+}
+
+// msg025
+function onMMSTest()
+{
+    onIncomingMessageCheck("onMMS");
+}
+
+// msg026
+function onEmailTest()
+{
+    onIncomingMessageCheck("onEmail");
+}
+
+function incomingMsgCb(msg)
+{
+    // empty
+}
+
+function onIncomingMessageCheck(func)
+{
+    try
+    {
+        var handler = MsgObj[func](incomingMsgCb);
+        TestEngine.test("No error thrown from: messaging." + func + " (1)", true);
+        var handler2 = MsgObj[func](incomingMsgCb);
+        TestEngine.test("No error thrown from: messaging." + func + " (2)", true);
+
+        // is still should be impossible to unsubscribe with invalid args
+        invalidUnsubscribeCheck();
+
+        TestEngine.test("Checking type of returned handle (1)", isNumber(handler));
+        TestEngine.test("Checking value of returned handle (1)", handler >= 0);
+        TestEngine.test("Checking type of returned handle (2)", isNumber(handler2));
+        TestEngine.test("Checking value of returned handle (2)", handler2 >= 0);
+        TestEngine.test("Comparing values of returned handles", handler != handler2);
+
+        MsgObj.unsubscribe(handler);
+        TestEngine.test("No error thrown from: messaging.unsubscribe (1)", true);
+        MsgObj.unsubscribe(handler2);
+        TestEngine.test("No error thrown from: messaging.unsubscribe (2)", true);
+        MsgObj.unsubscribe(handler);
+        TestEngine.test("No error thrown from: messaging.unsubscribe after unsubscribing (1)", true);
+        MsgObj.unsubscribe(handler2);
+        TestEngine.test("No error thrown from: messaging.unsubscribe after unsubscribing (2)", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+// msg027
+function attachmentPrecondition()
+{
+    // resolve image directory
+    function on_resolve_success(dir) {
+        imageDir = dir;
+        TestEngine.test("Attachment precondition passed",true);
+
+        // create attachment file
+        try {
+            imageDir.createFile(filename1);
+            imageDir.createFile(filename2);
+            imageDir.createFile(filename3);
+        }
+        catch (error) {
+            TestEngine.test("File already exists. Ignoring",error.code == 100); // IO_ERR
+        }
+
+        file1 = imageDir.resolve(filename1);
+        TestEngine.test("checking file1", file1 != null && file1 != undefined)
+
+        file2 = imageDir.resolve(filename2);
+        TestEngine.test("checking file2", file2 != null && file2 != undefined)
+
+        file3 = imageDir.resolve(filename3);
+        TestEngine.test("checking file3", file3 != null && file3 != undefined)
+    }
+    function on_resolve_error() {
+        TestEngine.test("Attachment precondition failed",false);
+    }
+    var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+       FsObj.resolve(cb.successCallback, cb.errorCallback, "music");
+}
+
+// msg028
+function attachmentSMSTest()
+{
+    // for sms attachments MUST be ignored
+    var msg = MsgObj.createMessage(MsgObj.TYPE_SMS);
+    msg.body = "body";
+    msg.to = destinationPhoneNumbers;
+
+    // check attachments array
+    var att = new Array();
+    att[0] = file1;
+    msg.attachments = att;
+
+    // check sending attachments
+    function sendSuccess() {
+        TestEngine.test("Message sent successfully",true);
+    }
+
+    function sendFail() {
+        TestEngine.test("Message sending failed",false);
+    }
+
+    var cbObj = TestEngine.registerCallback("sendMessage", sendSuccess, sendFail);
+    MsgObj.sendMessage(cbObj.successCallback, cbObj.errorCallback, msg);
+}
+
+// msg029
+function attachmentMMSTest()
+{
+    attachmentCheck(MsgObj.TYPE_MMS);
+}
+
+// msg030
+function attachmentEmailTest()
+{
+    attachmentCheck(MsgObj.TYPE_EMAIL);
+}
+
+function attachmentCheck(type)
+{
+    var msg = MsgObj.createMessage(type);
+    msg.subject = "subject";
+    msg.body = "body";
+    msg.to = destinationPhoneNumbers;
+    if(type === MsgObj.TYPE_EMAIL) {
+        msg.to = destinationEmails;
+    }
+
+    msg.attachments = new Array(file1,file2,file3);
+
+    // check sending attachments
+    function sendSuccess() {
+        TestEngine.test("Message sent successfully",true);
+    }
+
+    function sendFail() {
+        TestEngine.test("Message sending failed",false);
+    }
+
+    var cbObj = TestEngine.registerCallback("sendMessage", sendSuccess, sendFail);
+    MsgObj.sendMessage(cbObj.successCallback, cbObj.errorCallback, msg);
+}
+
+// msg031
+function updateTestSMS()
+{
+    updateCheck(MsgObj.TYPE_SMS);
+}
+
+// msg032
+function updateTestMMS()
+{
+    updateCheck(MsgObj.TYPE_MMS);
+}
+
+// msg033
+function updateTestEmail()
+{
+    updateCheck(MsgObj.TYPE_EMAIL);
+}
+
+function updateCheck(type)
+{
+    TestEngine.log("Checking update function for message type: " + type);
+    var read;
+    var body;
+    var msg;
+
+    var addr1 = "+48123456789";
+    if(type === MsgObj.TYPE_EMAIL) {
+        addr1 = "aaa@bbb.com";
+    }
+
+    ///////////////  3   //////////////////
+    function updateSuccess2(msg) {
+        TestEngine.test("updateSuccess (2)" , true);
+
+        ///////////////  4   //////////////////
+        function findChangedSuccess(messages) {
+            TestEngine.test("findChangedSuccess",true);
+
+            // and compare it
+            TestEngine.test("Comparing 'body' attribute", changedBody != messages[0].body); // should not be changed
+
+            // invalid arguments
+            TestEngine.catchErrorType("code",17, messages[0], "update");
+            TestEngine.catchErrorType("code",17, messages[0], "update", 666, updateFailure);
+        }
+
+        function findChangesFailure() {
+            TestEngine.test("findChangesFailure",false);
+        }
+
+        var filter = { id:msg.id };
+        var cb6 = TestEngine.registerCallback("findMessages2", findChangedSuccess, findChangesFailure)
+        MsgObj.findMessages(cb6.successCallback, cb6.errorCallback, filter)
+    }
+
+    ///////////////  2   //////////////////
+    // find callbacks
+    function findSuccess(messages) {
+        TestEngine.logOK("findSuccess, messages=" +messages+ ", msg count=" + messages.length);
+        TestEngine.test("found messages", messages.length > 0);
+
+        // update isRead attribute (should pass)
+        read = messages[0].isRead;
+        messages[0].isRead = !read;
+        messages[0].body = changedBody;
+        var cb4 = TestEngine.registerCallback("update2", updateSuccess2, updateFailure);
+        messages[0].update(cb4.successCallback, cb4.errorCallback);
+    }
+
+    function findFailure(result) {
+        TestEngine.test("findFailure, result.code=" + result.code, false);
+    }
+
+    function updateFailure() {
+        TestEngine.test("updateFailure",false);
+    }
+
+
+    ///////////////  1   //////////////////
+    // send callbacks
+    function sendSuccess() {
+        TestEngine.test("sendSuccess" , true);
+
+        var filter = { body:"first message%",folder:[MsgObj.FOLDER_OUTBOX,MsgObj.FOLDER_SENTBOX]  };
+
+        var cb3 = TestEngine.registerCallback("findMessages", findSuccess, findFailure)
+        MsgObj.findMessages(cb3.successCallback, cb3.errorCallback, filter)
+    }
+
+    function sendFailure() {
+        TestEngine.test("sendFailure" , false);
+    }
+
+    // update created message
+    msg = MsgObj.createMessage(type);
+    msg.body = "first message"
+    msg.to = [addr1];
+    msg.isRead = true;
+    var cb = TestEngine.registerCallback("sendMessage", sendSuccess, sendFailure);
+    MsgObj.sendMessage(cb.successCallback, cb.errorCallback, msg);
+}
+
+// msg034
+function cancelingSendingTest()
+{
+    var canceled = false;
+    function errorCallback() {
+        TestEngine.test("sending error callback", false);
+    }
+    function successCallback() {
+        TestEngine.test("sending success callback", !canceled);
+    }
+
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    TestEngine.test("Checking message ",msg != undefined);
+
+    if(msg != undefined) {
+        msg.to = destinationEmails;
+        msg.body = "body";
+
+        var cObj = TestEngine.registerCallback("send", successCallback, errorCallback)
+        var pendingOperation = MsgObj.sendMessage(cObj.successCallback, cObj.errorCallback, msg);
+
+        canceled = pendingOperation.cancel();
+        TestEngine.test("Canceling MsgObj.sendMessage. Cancelled: " + canceled, true);
+        if (canceled) {
+            TestEngine.callbackMutex--;
+        }
+    }
+}
+
+// msg035
+function cancelingFindingTest()
+{
+    var canceled = false;
+    function errorCallback() {
+        TestEngine.test("find error callback", false);
+    }
+    function successCallback() {
+        TestEngine.test("find success callback", !canceled);
+    }
+    var cObj = TestEngine.registerCallback("find", successCallback, errorCallback)
+
+    var msg = { body:"body" };
+    var pendingOperation = MsgObj.findMessages(cObj.successCallback, cObj.errorCallback, msg);
+
+    canceled = pendingOperation.cancel();
+    TestEngine.test("Canceling MsgObj.findMessage. Cancelled: " + canceled, true);
+    if (canceled) {
+        TestEngine.callbackMutex--;
+    }
+}
+
+// msg036
+function cancelingUpdateTest()
+{
+    function errorCallback(err) {
+        TestEngine.test("sending error callback [" + err.code + "]", false);
+    }
+
+    function successCallback() {
+        TestEngine.test("sending success callback", true);
+
+        var canceled = false;
+
+        function updateSuccess(msg)
+        {
+            TestEngine.test("update() canceled = " + canceled, !canceled);
+        }
+
+        function updateError(err)
+        {
+            TestEngine.test("update() [" + err.code + "]", false);
+        }
+
+        var cObj = TestEngine.registerCallback("update", updateSuccess, updateError);
+        var pendingOperation = msg.update(cObj.successCallback, cObj.errorCallback);
+        if (pendingOperation != null)
+        {
+            canceled = pendingOperation.cancel();
+            TestEngine.test("Canceling Message.update. Cancelled: " + canceled, true);
+            if (canceled) {
+                TestEngine.callbackMutex--;
+            }
+        }
+    }
+
+    // create message
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+    TestEngine.test("Checking message ", msg != undefined);
+
+    if (msg != undefined) {
+        msg.body = "first message"
+        msg.to = ["wrt.spam@samsung.com"];
+        msg.isRead = true;
+
+        var cObj = TestEngine.registerCallback("send", successCallback, errorCallback);
+        MsgObj.sendMessage(cObj.successCallback, cObj.errorCallback, msg);
+    }
+}
+
+function compareAttachments(att1,att2)
+{
+    if(att1 === undefined && att2 === undefined) {
+        TestEngine.test("Both attachments are undefined", true);
+        return;
+    }
+    if(att1 === undefined || att2 === undefined) {
+        TestEngine.test("Attachment is undefined", false);
+        return;
+    }
+    TestEngine.test("Comparing attachments " + att1.fullPath + " with " + att2.fullPath, att1.fullPath == att2.fullPath);
+}
+
+function checkAttachmentsLength(att,len)
+{
+    TestEngine.test("Checking attachments length. Expected:" + len + " supplied:" + att.length, len === att.length);
+}
+
+// msg037
+function attachmentsIndexTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check indexes
+    msg.attachments[0] = file1;
+    checkAttachmentsLength(msg.attachments,1);
+    compareAttachments(msg.attachments[0],file1);
+    try
+    {
+        msg.attachments[2] = file2;
+    }
+    catch (e)
+    {
+        TestEngine.test("ERR: Injecting sparse (undefined) items.", (e.code == TYPE_MISMATCH_ERR));
+    }
+}
+
+// msg038
+function attachmentsConcatTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check concat
+    msg.attachments = new Array(file1);
+    var att = new Array(file2,file1);
+    var att2 = msg.attachments.concat(att);
+    checkAttachmentsLength(msg.attachments,1);
+    checkAttachmentsLength(att2,3);
+    compareAttachments(att2[0],file1);
+    compareAttachments(att2[1],file2);
+    compareAttachments(att2[2],file1);
+}
+
+// msg039
+function attachmentsPopTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check pop
+    msg.attachments = new Array(file1,file2);
+    var last = msg.attachments.pop();
+    checkAttachmentsLength(msg.attachments,1);
+    compareAttachments(last,file2);
+    compareAttachments(msg.attachments[0],file1);
+}
+
+// msg040
+function attachmentsPushTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check push
+    msg.attachments = new Array(file1);
+    var len = msg.attachments.push(file2);
+    checkAttachmentsLength(msg.attachments,2);
+    checkAttachmentsLength(msg.attachments,len);
+    compareAttachments(msg.attachments[1],file2);
+}
+
+// msg041
+function attachmentsReverseTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check reverse
+    msg.attachments = new Array(file1,file2);
+    msg.attachments.reverse();
+    compareAttachments(msg.attachments[1],file1);
+    compareAttachments(msg.attachments[0],file2);
+    checkAttachmentsLength(msg.attachments,2);
+}
+
+// msg042
+function attachmentsShiftTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check shift
+    msg.attachments = new Array(file1,file2);
+    var first = msg.attachments.shift();
+    checkAttachmentsLength(msg.attachments,1);
+    compareAttachments(first,file1);
+    compareAttachments(msg.attachments[0],file2);
+}
+
+// msg043
+function attachmentsSliceTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check slice
+    msg.attachments = new Array(file1,file2,file3,file1);
+    var sliced = msg.attachments.slice(1,3);
+    checkAttachmentsLength(sliced,2);
+    compareAttachments(sliced[0],file2);
+    compareAttachments(sliced[1],file3);
+}
+
+// msg044
+function attachmentsSpliceTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    //check splice
+    msg.attachments = new Array(file1,file2,file3,file2);
+    var spliced = msg.attachments.splice(1,10,file3,file2);
+    checkAttachmentsLength(spliced,3);
+    compareAttachments(spliced[0],file2);
+    compareAttachments(spliced[1],file3);
+    compareAttachments(spliced[2],file2);
+    checkAttachmentsLength(msg.attachments,3);
+    compareAttachments(msg.attachments[0],file1);
+    compareAttachments(msg.attachments[1],file3);
+    compareAttachments(msg.attachments[2],file2);
+}
+
+// msg045
+function attachmentsUnshiftTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check unshift
+    msg.attachments = new Array(file1,file2,file3);
+    var len = msg.attachments.unshift(file2);
+    checkAttachmentsLength(msg.attachments,4);
+    checkAttachmentsLength(msg.attachments,len);
+    compareAttachments(msg.attachments[0],file2);
+    compareAttachments(msg.attachments[1],file1);
+}
+
+
+//=============================================================================
+
+TestEngine.setTestSuiteName("[WAC2.0][Messaging]", 2*60*1000); //2min time out for callbacks
+//TestEngine.addTest(true, presenceTest, "[WAC2.0][Messaging] messaging functions presence test");
+//TestEngine.addTest(true, createMMSTest, "[WAC2.0][Messaging] create MMS test");
+TestEngine.addTest(true, createSMSTest, "[WAC2.0][Messaging] create SMS test");
+//TestEngine.addTest(true, createEmailTest, "[WAC2.0][Messaging] create email test");
+//TestEngine.addTest(true, createMessageInvalidParamsTest, "[WAC2.0][Messaging] create message function with invalid params test");
+//TestEngine.addTest(true, sendMMSTest, "[WAC2.0][Messaging] send MMS test");
+//TestEngine.addTest(true, sendSMSTest, "[WAC2.0][Messaging] send SMS test");
+//TestEngine.addTest(true, sendEmailTest, "[WAC2.0][Messaging] send Email test");
+//TestEngine.addTest(true, sendMessageInvalidParamsTest, "[WAC2.0][Messaging] send message function with invalid params test");
+//TestEngine.addTest(true, findNoEmailTest, "[WAC2.0][Messaging] find no EMail test");
+//TestEngine.addTest(true, findNoSMSTest, "[WAC2.0][Messaging] find no SMS test");
+//TestEngine.addTest(true, findNoMMSTest, "[WAC2.0][Messaging] find no MMS test");
+//TestEngine.addTest(true, findEmailTest, "[WAC2.0][Messaging] find EMail test");
+//TestEngine.addTest(true, findSMSTest, "[WAC2.0][Messaging] find SMS test");
+//TestEngine.addTest(true, findMMSTest, "[WAC2.0][Messaging] find MMS test");
+//TestEngine.addTest(true, findMessageInvalidParamsTest, "[WAC2.0][Messaging] find message function invalid params test");
+//TestEngine.addTest(true, unsubscribeInvalidTest, "[WAC2.0][Messaging] unsubscribe function with invalid args test");
+//TestEngine.addTest(true, onSMSInvalidTest, "[WAC2.0][Messaging] onSMS function test with invalid values");
+//TestEngine.addTest(true, onMMSInvalidTest, "[WAC2.0][Messaging] onMMS function test with invalid values");
+//TestEngine.addTest(true, onEmailInvalidTest, "[WAC2.0][Messaging] onEmail function test with invalid values");
+//TestEngine.addTest(true, onSMSTest, "[WAC2.0][Messaging] onSMS function test");
+//TestEngine.addTest(true, onMMSTest, "[WAC2.0][Messaging] onMMS function test");
+//TestEngine.addTest(true, onEmailTest, "[WAC2.0][Messaging] onEmail function test");
+//TestEngine.addTest(true, attachmentPrecondition, "[WAC2.0][Messaging] attachment tests precondition");
+//TestEngine.addTest(true, attachmentsIndexTest, "[WAC2.0][Messaging] attachment index tests");
+//TestEngine.addTest(true, attachmentsConcatTest, "[WAC2.0][Messaging] attachment concat tests");
+//TestEngine.addTest(true, attachmentsPopTest, "[WAC2.0][Messaging] attachment pop tests");
+//TestEngine.addTest(true, attachmentsPushTest, "[WAC2.0][Messaging] attachment push tests");
+//TestEngine.addTest(true, attachmentsReverseTest, "[WAC2.0][Messaging] attachment reverse tests");
+//TestEngine.addTest(true, attachmentsShiftTest, "[WAC2.0][Messaging] attachment shift tests");
+//TestEngine.addTest(true, attachmentsSliceTest, "[WAC2.0][Messaging] attachment slice tests");
+//TestEngine.addTest(true, attachmentsSpliceTest, "[WAC2.0][Messaging] attachment splice tests");
+//TestEngine.addTest(true, attachmentsUnshiftTest, "[WAC2.0][Messaging] attachment unshift tests");
+//TestEngine.addTest(true, attachmentSMSTest, "[WAC2.0][Messaging] SMS attachment test");
+//TestEngine.addTest(true, attachmentMMSTest, "[WAC2.0][Messaging] MMS attachment test");
+//TestEngine.addTest(true, attachmentEmailTest, "[WAC2.0][Messaging] Email attachment test");
+//TestEngine.addTest(true, updateTestSMS, "[WAC2.0][Messaging] Sms update test");
+//TestEngine.addTest(true, updateTestMMS, "[WAC2.0][Messaging] Mms update test");
+//TestEngine.addTest(true, updateTestEmail, "[WAC2.0][Messaging] Email update test");
+//TestEngine.addTest(true, cancelingSendingTest, "[WAC2.0][Messaging] Canceling sendMessage test");
+//TestEngine.addTest(true, cancelingFindingTest, "[WAC2.0][Messaging] Canceling findMessage test");
+//TestEngine.addTest(true, cancelingUpdateTest, "[WAC2.0][Messaging] Canceling message update test");
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestOrientation.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestOrientation.js
new file mode 100644 (file)
index 0000000..16c0340
--- /dev/null
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test Orientation class.
+ *
+ * @author      xiangguo.qi (xiangguo.qi @samsung.com)
+ * @version     0.1
+ */
+
+
+var OrientationObj = deviceapis.orientation;
+var OrientationWatchID = "";
+
+// Orientation001
+function presenceTest()
+{
+    TestEngine.test("Checking checking", true);
+    TestEngine.test("Checking deviceapis object", deviceapis);
+    TestEngine.test("Checking Orientation object", OrientationObj);
+
+    TestEngine.test("Checking type of getCurrentOrientation", isFunction(OrientationObj.getCurrentOrientation));
+    TestEngine.test("Checking type of watchOrientation", isFunction(OrientationObj.watchOrientation));
+    TestEngine.test("Checking type of clearWatch", isFunction(OrientationObj.clearWatch));
+}
+
+function getSuccess(orientation)
+{
+    TestEngine.test("get current orientation", true);
+    TestEngine.test("orientation.alpha", isNumber(orientation.alpha));
+    TestEngine.test("orientation.beta", isNumber(orientation.beta));
+    TestEngine.test("orientation.gamma", isNumber(orientation.gamma));
+}
+
+function getFail()
+{
+    TestEngine.test("get current orientation", false);
+}
+
+//Orientation002
+function getCurrentOrientationValidParameters()
+{
+    var cbObj = TestEngine.registerCallback("getCurrentOrientation", getSuccess, getFail, 3);
+    try {
+        OrientationObj.getCurrentOrientation(cbObj.successCallback, cbObj.errorCallback);
+        TestEngine.test("exception not thrown", true);
+    } catch(e) {
+        TestEngine.logErr("Exception should not be thrown" + e);
+    }
+    try {
+        OrientationObj.getCurrentOrientation(cbObj.successCallback);
+        TestEngine.test("exception not thrown", true);
+    } catch(e) {
+        TestEngine.logErr("Exception should not be thrown" + e);
+    }
+    try {
+        OrientationObj.getCurrentOrientation(cbObj.successCallback, undefined);
+        TestEngine.test("exception not thrown", true);
+    } catch(e) {
+        TestEngine.logErr("Exception should not be thrown" + e);
+    }
+
+}
+
+// Orientation003
+function getCurrentOrientationInvalidParamsTest()
+{
+    TestEngine.catchErrorType("code",17, OrientationObj, "getCurrentOrientation", 1234, undefined);
+    TestEngine.catchErrorType("code",17, OrientationObj, "getCurrentOrientation", "test");
+    TestEngine.catchErrorType("code",17, OrientationObj, "getCurrentOrientation", new Date());
+    TestEngine.catchErrorType("code",17, OrientationObj, "getCurrentOrientation", [6, 6, 6]);
+}
+
+
+function successFail()
+{
+    TestEngine.test("Correctly onError called", true);
+}
+
+// Orientation004
+function getCurrentOrientationCheckErrorCallback()
+{
+    var failObj = TestEngine.registerCallback("getCurrentOrientation", getSuccess, successFail);
+    try {
+        OrientationObj.getCurrentOrientation(undefined, failObj.errorCallback);
+    } catch(e) {
+        TestEngine.logErr("Exception should not be thrown" + e);
+    }
+    try {
+        OrientationObj.getCurrentOrientation(1234, failObj.errorCallback);
+        TestEngine.logErr("Exception should be thrown");
+    } catch(e) {
+        TestEngine.logOK("Exception thrown" + e);
+    }
+}
+
+
+// Orientation005
+function watchOrientationInvalidParamsTest()
+{
+    TestEngine.catchErrorType("code",17, OrientationObj, "watchOrientation", "test");
+    TestEngine.catchErrorType("code",17, OrientationObj, "watchOrientation", new Date());
+    TestEngine.catchErrorType("code",17, OrientationObj, "watchOrientation", [6, 6, 6]);
+}
+
+// Orientation006
+function watchOrientationCheck()
+{
+    function watchSuccess(orientation)
+    {
+        OrientationObj.clearWatch(OrientationWatchID);
+        TestEngine.test("watch orientation",true);
+        TestEngine.test("orientation.alpha", isNumber(orientation.alpha));
+        TestEngine.test("orientation.beta", isNumber(orientation.beta));
+        TestEngine.test("orientation.gamma", isNumber(orientation.gamma));
+    }
+
+    function watchFail()
+    {
+        TestEngine.test("watch orientation",false);
+    }
+
+    var cbObj = TestEngine.registerCallback("watchOrientation", watchSuccess, watchFail);
+    try {
+        OrientationWatchID = OrientationObj.watchOrientation(cbObj.successCallback, cbObj.errorCallback, {
+            minNotificationInterval:20
+            });
+        TestEngine.logOK("No exception thrown");
+    } catch (e) {
+        TestEngine.logErr("Exception should not be thrown" + e.toString());
+    }
+}
+
+// Orientation007
+function clearWatchTest()
+{
+    try
+    {
+        OrientationObj.clearWatch(OrientationWatchID);
+        TestEngine.logOK("clearWatch OK");
+    }
+    catch (error) {
+        TestEngine.logErr("clearWatch Error");
+    }
+    try
+    {
+        OrientationObj.clearWatch(undefined);
+        TestEngine.logOK("clearWatch OK");
+    }
+    catch (error) {
+        TestEngine.logErr("clearWatch Error");
+    }
+    try
+    {
+        OrientationObj.clearWatch(null);
+        TestEngine.logOK("clearWatch OK");
+    }
+    catch (error) {
+        TestEngine.logErr("clearWatch Error");
+    }
+}
+
+
+//=============================================================================
+TestEngine.setTestSuiteName("[WAC2.0][Orientation]", 2*1000); //2sec time out for callbacks
+//TestEngine.addTest(true, presenceTest, "[WAC2.0][Orientation] Orientation functions presence test");
+TestEngine.addTest(true, getCurrentOrientationValidParameters, "[WAC2.0][Orientation] Valid parameters");
+//TestEngine.addTest(true, getCurrentOrientationInvalidParamsTest, "[WAC2.0][Orientation] getCurrentOrientation invalid params  test");
+//TestEngine.addTest(true, getCurrentOrientationCheckErrorCallback, "[WAC2.0][Orientation] getCurrentOrientation test");
+//TestEngine.addTest(true, watchOrientationInvalidParamsTest, "[WAC2.0][Orientation] watchOrientation invalid params  test");
+//TestEngine.addTest(true, watchOrientationCheck, "[WAC2.0][Orientation] watchtAcceleration test");
+//TestEngine.addTest(true, clearWatchTest, "[WAC2.0][Orientation] clearWatch test");
+
+
diff --git a/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestTask.js b/tests/smack_security/smackSecurityTest1/js/WAC2.0/TestTask.js
new file mode 100644 (file)
index 0000000..cceb2ad
--- /dev/null
@@ -0,0 +1,919 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test task class.
+ *
+ * @author      Shi Hezhang (hezhang.shi@samsung.com)
+ * @author      Pan Rui (r.pan@samsung.com)
+ * @version     0.1
+ */
+
+var TestTask = {
+    TYPE_MISMATCH_ERR: 17,
+    INVALID_VALUES_ERR: 22,
+    task: null,
+    Itask:null,
+    old_task:null,
+    num_tasks:null,
+    found_tasks:null,
+    all_tasks:null,
+    expectedErrorCode: null,
+
+       createTestEvent: function (response)
+    {
+        TestTask.task.createTask({description:'Test Task 1',
+                summary:'Task created to test Itask creation',
+                dueDate: new Date(2009, 3, 30, 10, 0),
+                status:0,
+                priority:0});
+    },
+
+    onSuccessNonExpected: function(response)
+    {
+        TestEngine.test("non expected successCallback invoked", false);
+    },
+
+    onErrorExpected: function(response)
+    {
+        TestEngine.test("expected errorCallback invoked", true);
+        TestEngine.testPresence("error code", response.code);
+        TestEngine.test("Error number, was: " + response.code + ', expected: ' + TestTask.expectedErrorCode, response.code == TestTask.expectedErrorCode);
+    },
+
+    onSuccess: function(response)
+    {
+        TestEngine.test("Callback success", true);
+    },
+
+    onErrorCb: function(response)
+    {
+        TestEngine.logErr("errorCallback invoked [" + response.code + ']');
+    },
+
+    //Cal001
+    test_modulePresence: function()
+    {
+        TestEngine.test("Calendar manager presence", deviceapis.pim.task);
+    },
+
+    //Cal002
+    test_taskProperties: function()
+    {
+        TestEngine.test("test property HIGH_PRIORITY", deviceapis.pim.task.taskproperties.HIGH_PRIORITY === 0);
+        TestEngine.test("test property MEDIUM_PRIORITY", deviceapis.pim.task.taskproperties.MEDIUM_PRIORITY  === 1);
+        TestEngine.test("test property LOW_PRIORITY", deviceapis.pim.task.taskproperties.LOW_PRIORITY === 2);
+        TestEngine.test("test property STATUS_COMPLETED", deviceapis.pim.task.taskproperties.STATUS_COMPLETED === 0);
+        TestEngine.test("test property STATUS_NEEDS_ACTION", deviceapis.pim.task.taskproperties.STATUS_NEEDS_ACTION === 1);
+        TestEngine.test("test property STATUS_IN_PROCESS", deviceapis.pim.task.taskproperties.STATUS_IN_PROCESS === 2);
+        TestEngine.test("test property STATUS_CANCELLED", deviceapis.pim.task.taskproperties.STATUS_CANCELLED === 3);
+    },
+
+    onSuccessGetTask: function (response)
+    {
+        TestEngine.test("Found tasks", response.length > 0);
+        TestTask.task=response[0];
+    },
+
+    //Cal003
+    test_getTask: function()
+    {
+        var cbObj = TestEngine.registerCallback("getTaskLists",
+            TestTask.onSuccessGetTask,
+            TestTask.onErrorCb);
+        deviceapis.pim.task.getTaskLists(cbObj.successCallback, cbObj.errorCallback);
+    },
+
+    //Cal004
+    test_getTaskNoCallbacks: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", "test1");
+    },
+
+    //Cal005
+    test_getTaskInvalidCallbacks: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", 1, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", TestTask.onErrorCb, 2);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", 1, 2);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", "test1", "test2");
+    },
+
+    //Cal006
+    test_taskMethodsPresence: function()
+    {
+        TestEngine.testPresence("task.createTask presence", TestTask.task.createTask);
+        TestEngine.testPresence("task.addTask presence", TestTask.task.addTask);
+        TestEngine.testPresence("task.updateTask presence", TestTask.task.updateTask);
+        TestEngine.testPresence("task.deleteTask presence", TestTask.task.deleteTask);
+        TestEngine.testPresence("task.findTasks presence", TestTask.task.findTasks);
+    },
+
+    //Cal007
+    test_getTaskName: function()
+    {
+        var cName = TestTask.task.name;
+        TestEngine.test("test getName", isString(cName) && cName.length > 0);
+        TestEngine.log("task name: " + cName);
+    },
+
+    //Cal008
+    test_getTaskType: function ()
+    {
+        var cType = TestTask.task.type;
+        TestEngine.test("test getType", cType === 0 || cType === 1);
+        TestEngine.log("task type: " + cType);
+
+    },
+
+    //Cal009
+    test_taskStaticProperties: function()
+    {
+        TestEngine.test("test property SIM_TASK", TestTask.task.SIM_TASK === 0);
+        TestEngine.test("test property DEVICE_TASK", TestTask.task.DEVICE_TASK === 1);
+    },
+
+    //Cal010
+    test_createEmptyTask: function()
+    {
+        TestTask.Itask = null;
+        TestTask.Itask = TestTask.task.createTask();
+        TestEngine.test("Itask created", TestTask.Itask != null);
+    },
+
+    //Cal011
+    test_taskAttributes: function()
+    {
+        var Itask = TestTask.task.createTask();
+        TestEngine.test("test attribute id - type: " + typeof Itask.id,
+            isString(Itask.id));
+        var oldId = Itask.id;
+        Itask.id = "test" + oldId;
+        TestEngine.test("attribute id is read only", Itask.id === oldId);
+        TestEngine.test("test attribute description - type: " + typeof Itask.description,
+            isString(Itask.description));
+        TestEngine.test("test attribute summary - type: " + typeof Itask.summary,
+            isString(Itask.summary));
+        //TestEngine.test("test attribute categories - type: " + typeof Itask.categories,
+         //   typeof Itask.categories == 'object' && Itask.categories.length == 0);
+        TestEngine.test("test attribute status - type: " + typeof Itask.status + ", value: " + Itask.status,
+            isNumber(Itask.status));
+         TestEngine.test("test attribute priority - type: " + typeof Itask.priority + ", value: " + Itask.priority,
+            isNumber(Itask.priority));
+    },
+
+    //Cal012
+    test_createTask: function()
+    {
+        var date = new Date(2009, 3, 30, 10, 0);
+        var newEvent = TestTask.task.createTask({
+               priority:1,
+               description:'Test Task 1',
+               summary:'Task created to test Itask creation',
+               dueDate: new Date(2009, 3, 30, 10, 0),
+               status:1
+          });
+               TestEngine.test("correct duration", newEvent.priority === 1);
+               TestEngine.test("correct duration", newEvent.status === 1);
+               TestEngine.test("Itask with param created ", newEvent);
+               TestEngine.test("correct description", newEvent.description === 'Test Task 1');
+               TestEngine.test("correct summary", newEvent.summary === 'Task created to test Itask creation');
+               TestEngine.test("correct dueDate", newEvent.dueDate.toString() === date.toString());
+    },
+
+    onSuccessAddTaskCountBefore: function(response)
+    {
+        TestEngine.log("onSuccessAddTaskCountBefore entered");
+        //save current number of tasks
+        TestTask.num_tasks = response.length;
+        //add new Itask
+        var objCb = TestEngine.registerCallback("onSuccessAddTaskCountBefore",
+            TestTask.onSuccessAddTaskAdd,
+            TestTask.onErrorCb);
+        TestTask.task.addTask(objCb.successCallback,
+            objCb.errorCallback,
+            TestTask.Itask);
+    },
+
+    onSuccessAddTaskAdd: function(response)
+    {
+        TestEngine.log("onSuccessAddTaskAdd entered");
+        //count the number of tasks
+        var objCb = TestEngine.registerCallback("onSuccessAddTaskAdd",
+            TestTask.onSuccessAddTaskCountAfter,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    onSuccessAddTaskCountAfter: function(response)
+    {
+        TestEngine.log("onSuccessAddTaskCountAfter entered");
+        TestEngine.test("Number of tasks increased", TestTask.num_tasks+1 == response.length);
+        //validate Itask
+        var eventValidated = false;
+        TestEngine.log("added Itask's id " + TestTask.Itask.id);
+        for (var i in response) {
+            if (TestTask.Itask.id != response[i].id) {
+                continue;
+            }
+            TestEngine.test("description the same", response[i].description === TestTask.Itask.description);
+            TestEngine.test("summary the same", response[i].summary === TestTask.Itask.summary);
+            TestEngine.test("dueDate the same", response[i].dueDate.toString() === TestTask.Itask.dueDate.toString());
+            TestEngine.test("status the same", response[i].status === TestTask.Itask.status);
+            TestEngine.test("priority the same", response[i].priority === TestTask.Itask.priority);
+            eventValidated = true;
+        }
+        TestEngine.test("Task has been validated", eventValidated)
+        TestTask.found_tasks=null;
+        TestTask.num_tasks=null;
+    },
+
+    //Cal013
+    test_addTask1: function()
+    {
+        TestTask.Itask = TestTask.task.createTask({
+                   description:'Task created to test Itask creation',
+                summary:'Test Task 1',
+                dueDate: new Date(2012, 11, 30, 10, 0),
+                status: deviceapis.pim.task.taskproperties.STATUS_COMPLETED,
+                priority: deviceapis.pim.task.taskproperties.HIGH_PRIORITY});
+        //save current number of tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessAddTaskCountBefore,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal014
+    test_addTask2: function()
+    {
+        TestTask.Itask = TestTask.task.createTask({
+                summary:'Test Task 2',
+                description:'Task created to test Itask creation',
+                dueDate: new Date(2012, 11, 30, 10, 0),
+                status: deviceapis.pim.task.taskproperties.STATUS_COMPLETED,
+                priority: deviceapis.pim.task.taskproperties.HIGH_PRIORITY});
+        TestTask.Itask.dueDate = new Date(2012, 10, 30, 10, 0);
+        //save current number of tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessAddTaskCountBefore,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal015
+    test_addTask3: function()
+    {
+        TestTask.Itask = TestTask.task.createTask({
+                summary:'Test Task 3',
+                description:'Task created to test Itask creation',
+                dueDate: new Date(2012, 11, 30, 10, 0),
+                status: 2,
+                priority: 0});
+        //save current number of tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessAddTaskCountBefore,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal016
+    test_addTask4: function()
+    {
+        TestTask.Itask = TestTask.task.createTask({
+                summary:'Test Task 4',
+                description:'Task created to test Itask creation',
+                dueDate: new Date(2012, 11, 30, 10, 0),
+                status: 0,
+                priority: 0});
+
+        //save current number of tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessAddTaskCountBefore,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal017
+    test_addTask5: function()
+    {
+        TestTask.Itask = TestTask.task.createTask({
+                summary:'Test Task 5',
+                description:'Task created to test Itask creation',
+                dueDate: new Date(2012, 11, 30, 10, 0),
+                status: 0,
+                priority: 0});
+        //save current number of tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessAddTaskCountBefore,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal018
+    test_addTaskNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask");
+    },
+
+    //Cal019
+    test_addTaskNullCallbacksParams: function()
+    {
+        var Itask = TestTask.createTestEvent();
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", 1, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", "test", TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", "test", TestTask.onErrorCb, Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, "test", Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", 1, 1, Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", "test", "test", Itask);
+    },
+
+    //Cal020
+    test_addTaskWrongEventParam: function()
+    {
+        TestTask.expectedErrorCode = TestTask.INVALID_VALUES_ERR;
+
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, 22);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, new Date());
+        var objCb1 = TestEngine.registerCallback("Add Itask with null Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.addTask(objCb1.successCallback,
+            objCb1.errorCallback,
+            null);
+
+        var objCb2 = TestEngine.registerCallback("Add Itask with undefined Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.addTask(objCb2.successCallback,
+            objCb2.errorCallback,
+            undefined);
+
+    },
+
+    onSuccessFindAllTasks: function(response)
+    {
+        TestEngine.test("FindAllTasks", response.length > 0);
+        TestTask.all_tasks=response;
+    },
+
+    //Cal021
+    test_findAllTasks: function()
+    {
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessFindAllTasks,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    onSuccessFindTaskWithFilterNoResults: function(response)
+    {
+        TestEngine.test("FindTasks with filter not found results", response.length == 0);
+        TestTask.num_tasks=null;
+    },
+
+    test_FindTasksWithFilterNoResults: function(filter)
+    {
+        if(filter) {
+            for(var i in filter) {
+                TestEngine.log("---Filter---: " + i + " : " + filter[i]);
+            }
+        }
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessFindTaskWithFilterNoResults,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback,
+            filter);
+    },
+
+    onSuccessFindTaskWithFilterSomeResults: function(response)
+    {
+        TestEngine.test("FindTasks with filter found results", response.length > 0);
+        TestTask.num_tasks=null;
+    },
+
+    test_FindTasksWithFilterSomeResults: function(filter)
+    {
+        if(filter) {
+            for(var i in filter) {
+                TestEngine.log("---Filter---: " + i + " : " + filter[i]);
+            }
+        }
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessFindTaskWithFilterSomeResults,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback,
+            filter);
+    },
+
+    //Cal022
+    test_findTasksId: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {id: TestTask.all_tasks[0].id});
+    },
+
+    //Cal023
+    test_findTasksSummary: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {summary:'Test Task 1'});
+    },
+
+    //Cal024
+    test_findTasksDescription: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {description:'Task created to test Itask creation'});
+    },
+
+    //Cal028~~~~~~~~~~~~
+    test_findTasksStatus: function()
+    {
+           var status1 = deviceapis.pim.task.taskproperties.STATUS_COMPLETED;
+           var status2 = deviceapis.pim.task.taskproperties.STATUS_IN_PROCESS;
+           var statusArray =new Array();
+               statusArray.push(status1);
+               statusArray.push(status2);
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {status: statusArray});
+    },
+
+    //Cal028~~~~~~~~~~~~
+    test_findTasksPriority: function()
+    {
+           var priority1 = deviceapis.pim.task.taskproperties.HIGH_PRIORITY;
+           var priority2 = deviceapis.pim.task.taskproperties.MEDIUM_PRIORITY;
+           var priorityArray =new Array();
+               priorityArray.push(priority1);
+               priorityArray.push(priority2);
+        TestEngine.test("Some priority to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {priority: priorityArray});
+    },
+
+
+    //Cal029
+    test_findTasksFullDueDate: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {initialDueDate: new Date(2010, 11, 30, 1, 0),
+             endDueDate: new Date(2012, 11, 30, 23, 0)});
+    },
+
+    //Cal030
+    test_findTasksInitialDueDate: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {initialDueDate: new Date(2010, 11, 30, 1, 0),
+              endDueDate: null});
+    },
+
+    //Cal031
+    test_findTasksEndDueDate: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {initialDueDate: null,
+              endDueDate: new Date(2012, 11, 30, 23, 0)});
+    },
+
+    //Cal032
+    test_findTasksEmptyFilter: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults({});
+    },
+
+    //Cal033
+    test_findTasksFullDueDateNoResults: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterNoResults(
+            {initialDueDate: new Date(1980, 11, 30, 1, 0),
+             endDueDate: new Date(1980, 11, 30, 23, 0)});
+    },
+
+    //Cal035
+    test_findTasksSummaryNoResults: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterNoResults(
+            {summary:'non existing summary'});
+    },
+
+    //Cal036
+    test_findTasksDescriptionNoResults: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterNoResults(
+            {description:'non existing description'});
+    },
+
+    //Cal037
+    test_findTasksIdNoResults: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterNoResults(
+            {id:"2000000"});
+    },
+
+    //Cal039
+    test_findTasksNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks");
+    },
+
+    //Cal040
+    test_findTasksNullCallbacksParams: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", TestTask.onSuccessNonExpected, 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", TestTask.onSuccessNonExpected, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", 1, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", "test", TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", 1, 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", "test", "test");
+    },
+
+    //Cal041
+    test_findTasksWrongFilterParam: function()
+    {
+        TestTask.expectedErrorCode = TestTask.TYPE_MISMATCH_ERR;
+        var objCb1 = TestEngine.registerCallback("Find tasks with null filter param",
+            TestTask.onSuccess,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb1.successCallback,
+            objCb1.errorCallback,
+            null);
+
+        var objCb2 = TestEngine.registerCallback("Find tasks with undefined filter param",
+            TestTask.onSuccess,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb2.successCallback,
+            objCb2.errorCallback,
+            undefined);
+
+        var objCb3 = TestEngine.registerCallback("Find tasks with null filter param",
+            TestTask.onSuccess,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb3.successCallback,
+            objCb3.errorCallback,
+            22);
+
+        var objCb4 = TestEngine.registerCallback("Find tasks with undefined filter param",
+            TestTask.onSuccess,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb4.successCallback,
+            objCb4.errorCallback,
+            "test");
+    },
+
+    //Cal042
+    test_updateTask: function()
+    {
+        if(TestTask.all_tasks.length > 0)
+        {
+            var all=TestTask.all_tasks;
+            TestTask.old_task=all[0];
+
+            //all_tasks.length is added to be sure that it is not
+            //result of previous update
+
+            all[0].description = "Updated"+all.length;
+            all[0].summary = "Updated";
+            TestTask.Itask = all[0];
+
+            var objCb = TestEngine.registerCallback("updateTask",
+                TestTask.onSuccessUpdateTask1,
+                TestTask.onErrorCb);
+            TestTask.task.updateTask(objCb.successCallback,
+                objCb.errorCallback,
+                TestTask.Itask);
+        }
+    },
+
+    onSuccessUpdateTask1: function(response)
+    {
+        TestEngine.log("onSuccessUpdateTask1 entered");
+        //find this Itask
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessUpdateTask2,
+            TestTask.onErrorCb);
+
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback,
+            {description: TestTask.Itask.description,
+                summary: TestTask.Itask.summary});
+    },
+
+    onSuccessUpdateTask2: function(response)
+    {
+        TestEngine.log("onSuccessUpdateTask2 entered");
+        TestTask.found_tasks=response;
+        TestTask.num_tasks = response.length;
+        if(TestTask.found_tasks.length>0)
+        {
+            var f_flag=0;
+            for(var i in TestTask.found_tasks)
+            {
+                if( TestTask.found_tasks[i].description == TestTask.Itask.description &&
+                    TestTask.found_tasks[i].summary == TestTask.Itask.summary)
+                {
+                    TestEngine.test("Update Itask", true);
+                    f_flag=1;
+                }
+            }
+
+            if(f_flag==0)
+            {
+                TestEngine.test("Update Itask", false);
+            }
+        }
+        else
+        {
+            TestEngine.test("Updated tasks found", false);
+        }
+
+        var objCb = TestEngine.registerCallback("updateTask",
+            TestTask.onSuccessUpdateTask3,
+            TestTask.onErrorCb);
+        TestTask.task.updateTask(objCb.successCallback,
+            objCb.errorCallback,
+            TestTask.old_task);
+
+    },
+
+    onSuccessUpdateTask3: function(response)
+    {
+        TestEngine.log("onSuccessUpdateTask3 entered");
+        TestEngine.test("Task restored from update", true);
+    },
+
+    //Cal043
+    test_updateTaskNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask");
+    },
+
+    //Cal044
+    test_updateTaskNullCallbacksParams: function()
+    {
+        var Itask = TestTask.createTestEvent();
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", 1, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", "test", TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", "test", TestTask.onErrorCb, Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, "test", Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", 1, 1, Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", "test", "test", Itask);
+    },
+
+    //Cal045
+    test_updateTaskWrongTaskParam: function()
+    {
+        TestTask.expectedErrorCode = TestTask.INVALID_VALUES_ERR;
+
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, 22);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, new Date());
+
+        var objCb1 = TestEngine.registerCallback("Update Itask with null Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.updateTask(objCb1.successCallback,
+            objCb1.errorCallback,
+            null);
+
+        var objCb2 = TestEngine.registerCallback("Update Itask with undefined Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.updateTask(objCb2.successCallback,
+            objCb2.errorCallback,
+            undefined);
+    },
+    //Cal046
+    test_deleteTask: function()
+    {
+        //find all tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessDeleteTask1,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    onSuccessDeleteTask1: function(response)
+    {
+        TestEngine.log("onSuccessDeleteTask1 entered");
+        TestEngine.test("FindAllTasks", response.length > 0);
+        TestTask.all_tasks=response;
+
+        if(TestTask.all_tasks.length > 0)
+        {
+            TestTask.old_task=TestTask.all_tasks.length;
+            TestTask.Itask = TestTask.all_tasks[0];
+
+            var objCb = TestEngine.registerCallback("deleteTask",
+                TestTask.onSuccessDeleteTask2,
+                TestTask.onErrorCb);
+            TestTask.task.deleteTask(objCb.successCallback,
+                objCb.errorCallback,
+                TestTask.Itask.id);
+        }
+        else
+        {
+            TestEngine.test("Events for delete found", false);
+        }
+    },
+
+    onSuccessDeleteTask2: function(response)
+    {
+        TestEngine.log("onSuccessDeleteTask2 entered");
+        //check number of tasks now
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessDeleteTask3,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    onSuccessDeleteTask3: function(response)
+    {
+        TestEngine.log("onSuccessDeleteTask3 entered");
+        TestTask.all_tasks=response;
+        var num_after=response.length;
+        TestEngine.test("deleteTask", num_after + 1 == TestTask.old_task );
+    },
+
+
+    //Cal047
+    test_deleteTaskNoParams: function()
+    {
+        TestEngine.catchErrorType("code", 17, TestTask.task, "deleteTask");
+    },
+
+    //Cal048
+    test_deleteTaskNullCallbacksParams: function()
+    {
+        var Itask = TestTask.createTestEvent();
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", "test", TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", 1, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", "test", TestTask.onErrorCb, 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", TestTask.onSuccessNonExpected, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", TestTask.onSuccessNonExpected, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", TestTask.onSuccessNonExpected, "test", 1);
+    },
+
+    //Cal049
+    test_deleteTaskWrongTaskParam: function()
+    {
+        TestTask.expectedErrorCode = TestTask.INVALID_VALUES_ERR;
+
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, new Date());
+
+        var objCb1 = TestEngine.registerCallback("Delete Itask with null Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.deleteTask(objCb1.successCallback,
+            objCb1.errorCallback,
+            null);
+
+        var objCb2 = TestEngine.registerCallback("Delete Itask with undefined Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.deleteTask(objCb2.successCallback,
+            objCb2.errorCallback,
+            undefined);
+    }
+};
+
+TestEngine.setTestSuiteName("[WAC2.0][Task]");
+
+//Cal001
+//TestEngine.addTest(true,TestTask.test_modulePresence, "[WAC2.0][Task] Test Task");
+//
+////Cal002
+//TestEngine.addTest(true,TestTask.test_taskProperties, "[WAC2.0][Task] Test Itask properties");
+////Cal003
+TestEngine.addTest(true,TestTask.test_getTask, "[WAC2.0][Task] Get task");
+//
+////Cal004
+//TestEngine.addTest(true,TestTask.test_getTaskNoCallbacks, "[WAC2.0][Task] Get task with no callbacks");
+////Cal005
+//TestEngine.addTest(true,TestTask.test_getTaskInvalidCallbacks, "[WAC2.0][Task] Get task with invalid callbacks");
+////Cal006
+//TestEngine.addTest(true,TestTask.test_taskMethodsPresence, "[WAC2.0][Task] Task methods presence");
+////Cal007
+//TestEngine.addTest(true,TestTask.test_getTaskName, "[WAC2.0][Task] Get task name");
+////Cal008
+//TestEngine.addTest(true,TestTask.test_getTaskType, "[WAC2.0][Task] Get task type");
+////Cal009
+//TestEngine.addTest(true,TestTask.test_taskStaticProperties, "[WAC2.0][Task] Task static properties");
+//
+////Cal010
+//TestEngine.addTest(true,TestTask.test_createEmptyTask, "[WAC2.0][Task] Create empty Itask");
+////Cal011
+//TestEngine.addTest(true,TestTask.test_taskAttributes, "[WAC2.0][Task] Itask attributes");
+////Cal012
+//TestEngine.addTest(true,TestTask.test_createTask, "[WAC2.0][Task] Create Itask");
+//
+////Cal013
+//TestEngine.addTest(true,TestTask.test_addTask1, "[WAC2.0][Task] Add event1");
+////Cal014
+//TestEngine.addTest(true,TestTask.test_addTask2, "[WAC2.0][Task] Add event2");
+////Cal015
+//TestEngine.addTest(true,TestTask.test_addTask3, "[WAC2.0][Task] Add event3");
+////Cal016
+//TestEngine.addTest(true,TestTask.test_addTask4, "[WAC2.0][Task] Add event4");
+////Cal017
+//TestEngine.addTest(true,TestTask.test_addTask5, "[WAC2.0][Task] Add event5");
+//
+////Cal018
+//TestEngine.addTest(true,TestTask.test_addTaskNoParams, "[WAC2.0][Task] Add Itask with no params");
+////Cal019
+//TestEngine.addTest(true,TestTask.test_addTaskNullCallbacksParams, "[WAC2.0][Task] Add Itask with wrong callbacks");
+////Cal020
+//TestEngine.addTest(true,TestTask.test_addTaskWrongEventParam, "[WAC2.0][Task] Add Itask with wrong Itask param");
+//
+////Cal021
+//TestEngine.addTest(true,TestTask.test_findAllTasks, "[WAC2.0][Task] Find all tasks");
+////Cal022
+//TestEngine.addTest(true,TestTask.test_findTasksId, "[WAC2.0][Task] Find tasks, filter: id");
+////Cal023
+//TestEngine.addTest(true,TestTask.test_findTasksSummary, "[WAC2.0][Task] Find tasks, filter: summary");
+////Cal024
+//TestEngine.addTest(true,TestTask.test_findTasksDescription, "[WAC2.0][Task] Find tasks, filter: description");
+////Cal025
+//TestEngine.addTest(true,TestTask.test_findTasksStatus, "[WAC2.0][Task] Find tasks, filter: status");
+//
+//TestEngine.addTest(true,TestTask.test_findTasksPriority, "[WAC2.0][Task] Find tasks, filter: priority");
+////Cal030
+//TestEngine.addTest(true,TestTask.test_findTasksInitialDueDate, "[WAC2.0][Task] Find tasks, filter: initialDueDate");
+////Cal031
+//TestEngine.addTest(true,TestTask.test_findTasksEndDueDate, "[WAC2.0][Task] Find tasks, filter: endDueDate");
+////Cal032
+//TestEngine.addTest(true,TestTask.test_findTasksEmptyFilter, "[WAC2.0][Task] Find tasks, filter: empty filter");
+//
+////Cal035
+//TestEngine.addTest(true,TestTask.test_findTasksSummaryNoResults, "[WAC2.0][Task] Find tasks, no results, filter: summary");
+////Cal036
+//TestEngine.addTest(true,TestTask.test_findTasksDescriptionNoResults, "[WAC2.0][Task] Find tasks, no results, filter: description");
+////Cal039
+//TestEngine.addTest(true,TestTask.test_findTasksNoParams, "[WAC2.0][Task] Find tasks with no params");
+////Cal040
+//TestEngine.addTest(true,TestTask.test_findTasksNullCallbacksParams, "[WAC2.0][Task] Find tasks with wrong callbacks");
+////Cal041
+//TestEngine.addTest(true,TestTask.test_findTasksWrongFilterParam, "[WAC2.0][Task] Find tasks with wrong filter param");
+//
+//TestEngine.addTest(true,TestTask.test_updateTask, "[WAC2.0][Task] Update Itask");
+////Cal043
+//TestEngine.addTest(true,TestTask.test_updateTaskNoParams, "[WAC2.0][Task] Update Itask with no params");
+////Cal044
+//TestEngine.addTest(true,TestTask.test_updateTaskNullCallbacksParams, "[WAC2.0][Task] Update Itask with wrong callbacks");
+////Cal045
+//TestEngine.addTest(true,TestTask.test_updateTaskWrongTaskParam, "[WAC2.0][Task] Update Itask with wrong Itask param");
+//
+////Cal046
+//TestEngine.addTest(true,TestTask.test_deleteTask, "[WAC2.0][Task] Delete Itask");
+////Cal047
+//TestEngine.addTest(true,TestTask.test_deleteTaskNoParams, "[WAC2.0][Task] Delete Itask with no params");
+////Cal048
+//TestEngine.addTest(true,TestTask.test_deleteTaskNullCallbacksParams, "[WAC2.0][Task] Delete Itask with wrong callbacks");
+////Cal049
+//TestEngine.addTest(true,TestTask.test_deleteTaskWrongTaskParam, "[WAC2.0][Task] Delete Itask with wrong Itask param");
diff --git a/tests/smack_security/smackSecurityTest1/js/include.js b/tests/smack_security/smackSecurityTest1/js/include.js
new file mode 100644 (file)
index 0000000..c5beab8
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestFilesystem.js")
+IncludeJavaScript("js/WAC2.0/TestCalendar.js")
+IncludeJavaScript("js/WAC2.0/TestContact.js")
+IncludeJavaScript("js/WAC2.0/TestAccelerometer.js")
+IncludeJavaScript("js/WAC2.0/TestOrientation.js")
+IncludeJavaScript("js/WAC2.0/TestTask.js")
+IncludeJavaScript("js/WAC2.0/TestCamera.js")
+IncludeJavaScript("js/WAC2.0/TestDeviceInteraction.js")
+IncludeJavaScript("js/WAC2.0/TestMessaging.js")
+IncludeJavaScript("js/WAC2.0/TestDevicestatus.js")
+
+IncludeJavaScript("js/WAC2.0/CloseCallback.js")
diff --git a/tests/smack_security/smackSecurityTest1/js/jquery.js b/tests/smack_security/smackSecurityTest1/js/jquery.js
new file mode 100644 (file)
index 0000000..381ebfe
--- /dev/null
@@ -0,0 +1,40 @@
+/*!
+ * Copyright (C) 2011, John Resig
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the "Software"), to deal in
+ * the Software without restriction, including without limitation the rights to
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is furnished to do
+ * so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+/*!
+ * jQuery JavaScript Library v1.7
+ * http://jquery.com/
+ *
+ * Copyright 2011, John Resig
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ * Copyright 2011, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ *
+ * Date: Thu Nov 3 16:18:21 2011 -0400
+ */
+
+(function(a,b){function cA(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cx(a){if(!cm[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cn||(cn=c.createElement("iframe"),cn.frameBorder=cn.width=cn.height=0),b.appendChild(cn);if(!co||!cn.createElement)co=(cn.contentWindow||cn.contentDocument).document,co.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),co.close();d=co.createElement(a),co.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cn)}cm[a]=e}return cm[a]}function cw(a,b){var c={};f.each(cs.concat.apply([],cs.slice(0,b)),function(){c[this]=a});return c}function cv(){ct=b}function cu(){setTimeout(cv,0);return ct=f.now()}function cl(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ck(){try{return new a.XMLHttpRequest}catch(b){}}function ce(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cd(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function cc(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bG.test(a)?d(a,e):cc(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)cc(a+"["+e+"]",b[e],c,d);else d(a,b)}function cb(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function ca(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bV,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=ca(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=ca(a,c,d,e,"*",g));return l}function b_(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bR),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bE(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bz:bA;if(d>0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bB(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function br(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bi,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bq(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bp(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bp)}function bp(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bo(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bn(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bm(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bl(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function X(a){var b=Y.split(" "),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function W(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(R.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(){return!0}function M(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function K(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(K,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z]|[0-9])/ig,x=/^-ms-/,y=function(a,b){return(b+"").toUpperCase()},z=d.userAgent,A,B,C,D=Object.prototype.toString,E=Object.prototype.hasOwnProperty,F=Array.prototype.push,G=Array.prototype.slice,H=String.prototype.trim,I=Array.prototype.indexOf,J={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=n.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7",length:0,size:function(){return this.length},toArray:function(){return G.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?F.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),B.add(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(G.apply(this,arguments),"slice",G.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:F,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;B.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!B){B=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",C,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",C),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&K()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return a!=null&&m.test(a)&&!isNaN(a)},type:function(a){return a==null?String(a):J[D.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!E.call(a,"constructor")&&!E.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||E.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(x,"ms-").replace(w,y)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:H?function(a){return a==null?"":H.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?F.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(I)return I.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=G.call(arguments,2),g=function(){return a.apply(c,f.concat(G.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=s.exec(a)||t.exec(a)||u.exec(a)||a.indexOf("compatible")<0&&v.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){J["[object "+b+"]"]=b.toLowerCase()}),A=e.uaMatch(z),A.browser&&(e.browser[A.browser]=!0,e.browser.version=A.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?C=function(){c.removeEventListener("DOMContentLoaded",C,!1),e.ready()}:c.attachEvent&&(C=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",C),e.ready())}),typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return e});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){return i.done.apply(i,arguments).fail.apply(i,arguments)},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var a=c.createElement("div"),b=c.documentElement,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;a.setAttribute("className","t"),a.innerHTML="   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/><nav></nav>",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,unknownElems:!!a.getElementsByTagName("nav").length,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",enctype:!!c.createElement("form").enctype,submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.lastChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},m&&f.extend(p,{position:"absolute",left:"-999px",top:"-999px"});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;f(function(){var a,b,d,e,g,h,i=1,j="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",l="visibility:hidden;border:0;",n="style='"+j+"border:5px solid #000;padding:0;'",p="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>";m=c.getElementsByTagName("body")[0];!m||(a=c.createElement("div"),a.style.cssText=l+"width:0;height:0;position:static;top:0;margin-top:"+i+"px",m.insertBefore(a,m.firstChild),o=c.createElement("div"),o.style.cssText=j+l,o.innerHTML=p,a.appendChild(o),b=o.firstChild,d=b.firstChild,g=b.nextSibling.firstChild.firstChild,h={doesNotAddBorder:d.offsetTop!==5,doesAddBorderForTableAndCells:g.offsetTop===5},d.style.position="fixed",d.style.top="20px",h.fixedPosition=d.offsetTop===20||d.offsetTop===15,d.style.position=d.style.top="",b.style.overflow="hidden",b.style.position="relative",h.subtractsBorderForOverflowNotVisible=d.offsetTop===-5,h.doesNotIncludeMarginInBodyOffset=m.offsetTop!==i,m.removeChild(a),o=a=null,f.extend(k,h))}),o.innerHTML="",n.removeChild(o),o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[f.expando]:a[f.expando]&&f.expando,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[f.expando]=n=++f.uuid:n=f.expando),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[f.expando]:f.expando;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)?b=b:b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" "));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[f.expando]:a.removeAttribute?a.removeAttribute(f.expando):a[f.expando]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];if(!arguments.length){if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}return b}e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!a||j===3||j===8||j===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g},removeAttr:function(a,b){var c,d,e,g,h=0;if(a.nodeType===1){d=(b||"").split(p),g=d.length;for(;h<g;h++)e=d[h].toLowerCase(),c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1)}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return b;h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/\.(.*)$/,A=/^(?:textarea|input|select)$/i,B=/\./g,C=/ /g,D=/[^\w\s.|`]/g,E=/^([^\.]*)?(?:\.(.+))?$/,F=/\bhover(\.\S+)?/,G=/^key/,H=/^(?:mouse|contextmenu)|click/,I=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,J=function(a){var b=I.exec(a);b&&
+(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},K=function(a,b){return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||a.id===b[2])&&(!b[3]||b[3].test(a.className))},L=function(a){return f.event.special.hover?a:a.replace(F,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=L(c).split(" ");for(k=0;k<c.length;k++){l=E.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,namespace:n.join(".")},p),g&&(o.quick=J(g),!o.quick&&f.expr.match.POS.test(g)&&(o.isPositional=!0)),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d){var e=f.hasData(a)&&f._data(a),g,h,i,j,k,l,m,n,o,p,q;if(!!e&&!!(m=e.events)){b=L(b||"").split(" ");for(g=0;g<b.length;g++){h=E.exec(b[g])||[],i=h[1],j=h[2];if(!i){j=j?"."+j:"";for(l in m)f.event.remove(a,l+j,c,d);return}n=f.event.special[i]||{},i=(d?n.delegateType:n.bindType)||i,p=m[i]||[],k=p.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;if(c||j||d||n.remove)for(l=0;l<p.length;l++){q=p[l];if(!c||c.guid===q.guid)if(!j||j.test(q.namespace))if(!d||d===q.selector||d==="**"&&q.selector)p.splice(l--,1),q.selector&&p.delegateCount--,n.remove&&n.remove.call(a,q)}else p.length=0;p.length===0&&k!==p.length&&((!n.teardown||n.teardown.call(a,j)===!1)&&f.removeEvent(a,i,e.handle),delete m[i])}f.isEmptyObject(m)&&(o=e.handle,o&&(o.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"",(g||!e)&&c.preventDefault();if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,n=null;for(m=e.parentNode;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length;l++){m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d);if(c.isPropagationStopped())break}c.type=h,c.isDefaultPrevented()||(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=(f.event.special[c.type]||{}).handle,j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click"))for(m=c.target;m!=this;m=m.parentNode||this){o={},q=[];for(k=0;k<e;k++)r=d[k],s=r.selector,t=o[s],r.isPositional?t=(t||(o[s]=f(s))).index(m)>=0:t===b&&(t=o[s]=r.quick?K(m,r.quick):f(m).is(s)),t&&q.push(r);q.length&&j.push({elem:m,matches:q})}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){p=j[k],c.currentTarget=p.elem;for(l=0;l<p.matches.length&&!c.isImmediatePropagationStopped();l++){r=p.matches[l];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=(i||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement wheelDelta".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},focus:{delegateType:"focusin",noBubble:!0},blur:{delegateType:"focusout",noBubble:!0},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?N:M):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=N;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=N;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=N,this.stopPropagation()},isDefaultPrevented:M,isPropagationStopped:M,isImmediatePropagationStopped:M},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]=f.event.special[b]={delegateType:b,bindType:b,handle:function(a){var b=this,c=a.relatedTarget,d=a.handleObj,e=d.selector,g,h;if(!c||d.origType===a.type||c!==b&&!f.contains(b,c))g=a.type,a.type=d.origType,h=d.handler.apply(this,arguments),a.type=g;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(A.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;A.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return A.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=M;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=M);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),G.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),H.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw"Syntax error, unrecognized expression: "+a};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var O=/Until$/,P=/^(?:parents|prevUntil|prevAll)/,Q=/,/,R=/^.[^:#\[\.,]*$/,S=Array.prototype.slice,T=f.expr.match.POS,U={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(W(this,a,!1),"not",a)},filter:function(a){return this.pushStack(W(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?T.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=T.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(V(c[0])||V(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var Y="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",Z=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,_=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,ba=/<([\w:]+)/,bb=/<tbody/i,bc=/<|&#?\w+;/,bd=/<(?:script|style)/i,be=/<(?:script|object|embed|option|style)/i,bf=new RegExp("<(?:"+Y.replace(" ","|")+")","i"),bg=/checked\s*(?:[^=]|=\s*.checked.)/i,bh=/\/(java|ecma)script/i,bi=/^\s*<!(?:\[CDATA\[|\-\-)/,bj={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bk=X(c);bj.optgroup=bj.option,bj.tbody=bj.tfoot=bj.colgroup=bj.caption=bj.thead,bj.th=bj.td,f.support.htmlSerialize||(bj._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){f(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after"
+,arguments);a.push.apply(a,f(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Z,""):null;if(typeof a=="string"&&!bd.test(a)&&(f.support.leadingWhitespace||!$.test(a))&&!bj[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(_,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bg.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bl(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,br)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!be.test(j)&&(f.support.checkClone||!bg.test(j))&&!f.support.unknownElems&&bf.test(j)&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bn(a,d),e=bo(a),g=bo(d);for(h=0;e[h];++h)g[h]&&bn(e[h],g[h])}if(b){bm(a,d);if(c){e=bo(a),g=bo(d);for(h=0;e[h];++h)bm(e[h],g[h])}}e=g=null;return d},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!bc.test(k))k=b.createTextNode(k);else{k=k.replace(_,"<$1></$2>");var l=(ba.exec(k)||["",""])[1].toLowerCase(),m=bj[l]||bj._default,n=m[0],o=b.createElement("div");b===c?bk.appendChild(o):X(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=bb.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&$.test(k)&&o.insertBefore(b.createTextNode($.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bq(k[i]);else bq(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bh.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bs=/alpha\([^)]*\)/i,bt=/opacity=([^)]*)/,bu=/([A-Z]|^ms)/g,bv=/^-?\d+(?:px)?$/i,bw=/^-?\d/,bx=/^([\-+])=([\-+.\de]+)/,by={position:"absolute",visibility:"hidden",display:"block"},bz=["Left","Right"],bA=["Top","Bottom"],bB,bC,bD;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bB(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bx.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bB)return bB(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bE(a,b,d);f.swap(a,by,function(){e=bE(a,b,d)});return e}},set:function(a,b){if(!bv.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bt.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bs,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bs.test(g)?g.replace(bs,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bB(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bC=function(a,c){var d,e,g;c=c.replace(bu,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bD=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bv.test(f)&&bw.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bB=bC||bD,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bF=/%20/g,bG=/\[\]$/,bH=/\r?\n/g,bI=/#.*$/,bJ=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bK=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bL=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bM=/^(?:GET|HEAD)$/,bN=/^\/\//,bO=/\?/,bP=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bQ=/^(?:select|textarea)/i,bR=/\s+/,bS=/([?&])_=[^&]*/,bT=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bU=f.fn.load,bV={},bW={},bX,bY,bZ=["*/"]+["*"];try{bX=e.href}catch(b$){bX=c.createElement("a"),bX.href="",bX=bX.href}bY=bT.exec(bX.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bU)return bU.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bP,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bQ.test(this.nodeName)||bK.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bH,"\r\n")}}):{name:b.name,value:c.replace(bH,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?cb(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),cb(a,b);return a},ajaxSettings:{url:bX,isLocal:bL.test(bY[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bZ},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:b_(bV),ajaxTransport:b_(bW),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cd(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=ce(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bJ.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bI,"").replace(bN,bY[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bR),d.crossDomain==null&&(r=bT.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bY[1]&&r[2]==bY[2]&&(r[3]||(r[1]==="http:"?80:443))==(bY[3]||(bY[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),ca(bV,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bM.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bO.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bS,"$1_="+x);d.url=y+(y===d.url?(bO.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bZ+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=ca(bW,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){s<2?w(-1,z):f.error(z)}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)cc(g,a[g],c,e);return d.join("&").replace(bF,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cf=f.now(),cg=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cf++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cg.test(b.url)||e&&cg.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cg,l),b.url===j&&(e&&(k=k.replace(cg,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ch=a.ActiveXObject?function(){for(var a in cj)cj[a](0,1)}:!1,ci=0,cj;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ck()||cl()}:ck,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ch&&delete cj[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++ci,ch&&(cj||(cj={},f(a).unload(ch)),cj[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cm={},cn,co,cp=/^(?:toggle|show|hide)$/,cq=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cr,cs=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],ct;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cw("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cx(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cw("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cw("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cx(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cp.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=cq.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cw("show",1),slideUp:cw("hide",1),slideToggle:cw("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=ct||cu(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cr&&(cr=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=ct||cu(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cr),cr=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now))}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cy=/^t(?:able|d|h)$/i,cz=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cA(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cy.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cz.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cz.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cA(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cA(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window);
diff --git a/tests/smack_security/smackSecurityTest2/config1.xml b/tests/smack_security/smackSecurityTest2/config1.xml
new file mode 100644 (file)
index 0000000..c95ee2a
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/smackSecurityTest1N"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://wacapps.net/api/filesystem" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/smack_security/smackSecurityTest2/config10.xml b/tests/smack_security/smackSecurityTest2/config10.xml
new file mode 100644 (file)
index 0000000..68d21c0
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/smackSecurityTest10N"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://wacapps.net/api/messaging" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/smack_security/smackSecurityTest2/config2.xml b/tests/smack_security/smackSecurityTest2/config2.xml
new file mode 100644 (file)
index 0000000..fc0e44b
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/smackSecurityTest2N"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://wacapps.net/api/pim.calendar" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/smack_security/smackSecurityTest2/config3.xml b/tests/smack_security/smackSecurityTest2/config3.xml
new file mode 100644 (file)
index 0000000..2ffb8d7
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/smackSecurityTest3N"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://wacapps.net/api/pim.contact" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/smack_security/smackSecurityTest2/config4.xml b/tests/smack_security/smackSecurityTest2/config4.xml
new file mode 100644 (file)
index 0000000..3104bdc
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/smackSecurityTest4N"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://wacapps.net/api/accelerometer" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/smack_security/smackSecurityTest2/config5.xml b/tests/smack_security/smackSecurityTest2/config5.xml
new file mode 100644 (file)
index 0000000..5e6b2ca
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/smackSecurityTest5N"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://wacapps.net/api/orientation" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/smack_security/smackSecurityTest2/config6.xml b/tests/smack_security/smackSecurityTest2/config6.xml
new file mode 100644 (file)
index 0000000..f78520e
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/smackSecurityTest6N"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://wacapps.net/api/pim.task" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/smack_security/smackSecurityTest2/config7.xml b/tests/smack_security/smackSecurityTest2/config7.xml
new file mode 100644 (file)
index 0000000..bdd1d70
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/smackSecurityTest7N"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://wacapps.net/api/camera" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/smack_security/smackSecurityTest2/config8.xml b/tests/smack_security/smackSecurityTest2/config8.xml
new file mode 100644 (file)
index 0000000..2d633d1
--- /dev/null
@@ -0,0 +1,26 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/smackSecurityTest8N"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://wacapps.net/api/deviceinteraction" required="true" />
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/smack_security/smackSecurityTest2/config9.xml b/tests/smack_security/smackSecurityTest2/config9.xml
new file mode 100644 (file)
index 0000000..9634abb
--- /dev/null
@@ -0,0 +1,27 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<widget xmlns="http://www.w3.org/ns/widgets"
+        id="http://test.samsung.com/widget/wac/smackSecurityTest9N"
+        version="1.0">
+    <name>WAC Test</name>
+    <description>WAC Test widget</description>
+    <author href="http://www.rd.samsung.pl/" email="w.bielawski@samsung.com;p.misiak@samsung.com">
+        SPRC
+    </author>
+    <license href="http://www.rd.samsung.pl/">
+        Example license Copyright (c) 2009 Samsung Corp.
+    </license>
+    <icon src="icon.png" height="75" width="75"/>
+    <content src="index.html" type="application/xhtml+xml"/>
+    <access network="true" plugins="true" SAMSUNG.alarm="true"/>
+    <update href="http://www.rd.samsung.pl/"/>
+
+
+    <feature name="http://wacapps.net/api/deviceapis" required="true"><param name="testProperty" value="testPropertyValue" /></feature>
+
+    <feature name="http://wacapps.net/api/devicestatus" required="true"/>
+
+    <!-- tag preference is required to test appconfig -->
+    <preference name="TestPreference" value="PreferenceValue"/>
+    <preference name="TestROPreference" value="ProtectedValue" readonly="true"/>
+
+</widget>
diff --git a/tests/smack_security/smackSecurityTest2/css/style.css b/tests/smack_security/smackSecurityTest2/css/style.css
new file mode 100644 (file)
index 0000000..a4629be
--- /dev/null
@@ -0,0 +1,35 @@
+/* Add style information here */
+* {
+    padding: 0px;
+    margin: 0px;
+    color: #000;
+}
+
+#summary {
+    background-color: #ddd;
+    color: #000;
+    padding: 2px;
+}
+
+#log {
+    color: #fff;
+    width: 400px;
+    display: block;
+}
+
+#log .entry {
+    color: #fff;
+    padding: 2px;
+}
+
+#log .passed {
+    background-color: #45DE1B;
+}
+
+#log .failed {
+    background-color: #DE1B1B;
+}
+
+#log .exception {
+    background-color: #DE1BD8;
+}
diff --git a/tests/smack_security/smackSecurityTest2/index.html b/tests/smack_security/smackSecurityTest2/index.html
new file mode 100644 (file)
index 0000000..2aa3d2f
--- /dev/null
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+    <head>
+        <title>Test engine</title>
+        <meta http-equiv="content-type"
+              content="text/html;charset=utf-8" />
+        <meta http-equiv="Content-Style-Type" content="text/css" />
+        <link rel="stylesheet" type="text/css" href="css/style.css" />
+        <script type="text/javascript" src="js/jquery.js"></script>
+        <!-- jquery.js has to be included first -->
+        <script type="text/javascript" src="js/include.js"></script>
+    </head>
+    <body bgColor="yellow" style="color:black;" onload="TestEngine.doTests();">
+        <div id="summary"></div>
+        <p id="log"></p>
+        <div id="video" style="background: red; width: 100%" />
+        TEST WIDGET
+   </body>
+</html>
+
diff --git a/tests/smack_security/smackSecurityTest2/js/TestEngine.js b/tests/smack_security/smackSecurityTest2/js/TestEngine.js
new file mode 100644 (file)
index 0000000..31c17bb
--- /dev/null
@@ -0,0 +1,1189 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test engine class.
+ *
+ * @author      Wojciech Bielawski(w.bielawski@samsung.com)
+ * @author      Pawel Misiak (p.misiak@samsung.com)
+ * @version     0.1
+ */
+
+var TestEngine = {
+    logText: "",
+    testCaseTimeout: 5 * 1000, //in miliseconds
+    currentCaseTimeout: 5 * 1000,
+    timer: null,
+    countOK: 0,
+    countErr: 0,
+    countException: 0,
+    countIgnored: 0,
+    currentFailings: [],
+    currentTestSuiteName: null,
+    callbackMutex: 0,
+    callbackMethodName: "",
+    currentTestCase: 0,
+    countAllPassed: 0,
+    countAllFailed: 0,
+    testCasesFailedCount: 0,
+    testCasesPassedCount: 0,
+    testCasesFailed: [],
+    testList: [],
+    finalLog: "\n",
+    testSuccessCallback: null,
+    testErrorCallback: null,
+    testSuiteName: null,
+    testSuiteStats: [],
+    resultLogger: new HTMLTestResultLogger('log'),
+    summaryRenderer: new HTMLTestSummaryRenderer('summary'),
+    finalCallback: null,
+
+    stepsArray: null,
+    stepTimeout: null,
+    currentStep: null,
+    errorType: null,
+    errorField: null,
+
+    /*
+     * Values used only as types representations.
+     */
+    STRING: '',
+    NUMBER: 0,
+    OBJECT: {},
+    ARRAY: [],
+    DATE: new Date(),
+    BOOL: false,
+    FUNCTION: function() {},
+
+    /*
+     * Error test possible results.
+     */
+    ERROR_TEST_RESULT: {
+      NOT_RUN: -4,
+      NOT_THROWN: -3,
+      BAD_TYPE: -2,
+      BAD_VALUE: -1,
+      OK: 0
+    },
+
+    /**
+     * Prints specified object in a TreeView like structure.
+     * @param obj Object to print.
+     * @param indent Must be undefined (don't pass anything).
+     */
+    dumpObject: function(obj, indent) {
+        if (indent === undefined) indent = '';
+        else indent += '   ';
+        var prefix = (indent.length == 0 ? indent : indent + '|--');
+        for (var i in obj) {
+            if (typeof(obj[i]) == "object") {
+                TestEngine.log(prefix + i + ":");
+                TestEngine.dumpObject(obj[i], indent);
+            }
+            else
+                TestEngine.log(prefix + i + ": " + obj[i]);
+        }
+    },
+
+    addTest: function(enabled, testFunc, testName, testPrereq)
+    {
+        if (null==testName) {
+            testName="unnamed test"
+        }
+        jsPrint("Add test: " + testName)
+        var data = new Object();
+        data.enabled = enabled;
+        data.testFunc = testFunc;
+        data.testName = testName;
+        data.testPrereq = testPrereq;
+        data.testSuite = TestEngine.testSuiteName;
+        // this.testList.push(testFunc)
+        this.testList.push(data);
+    },
+
+    setTestSuiteName: function(name, timeout)
+    {
+        this.testSuiteName = name;
+        this.testSuiteStats[name] = new Object();
+        this.testSuiteStats[name].passed = 0;
+        this.testSuiteStats[name].failed = 0;
+        this.testSuiteStats[name].assertsOK = 0;
+        this.testSuiteStats[name].assertsErr = 0;
+        TestEngine.currentCaseTimeout =
+            (timeout === undefined) ? TestEngine.testCaseTimeout : timeout;
+    },
+
+    setFinalCallback: function(finalCallbackParam)
+    {
+        this.finalCallback = finalCallbackParam;
+    },
+
+    log: function(text)
+    {
+        try
+        {
+            jsPrint(text);
+            this.logText += text + "<br/>";
+            this.finalLog += text + "\n";
+            // document.getElementById(TestEngine.currentTestSuite).innerHTML += text + "<br/>";
+            //document.getElementById('log').innerHTML += text + "<br/>";
+        }
+        catch(err)
+        {
+            this.countException++;
+            jsPrint("   TestEngine.log failure: " + err.message);
+        }
+    },
+
+    logException: function(text)
+    {
+        try
+        {
+            TestEngine.countException++;
+            TestEngine.log("[EXCEPTION] " + text);
+            TestEngine.currentFailings.push(text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logErr failure: " + err.message);
+        }
+    },
+
+    logErr: function(text)
+    {
+        try
+        {
+            TestEngine.countErr++;
+            TestEngine.log("[FAILED] " + text);
+            TestEngine.currentFailings.push(text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logErr failure: " + err.message);
+        }
+    },
+
+    logIgnored: function(text)
+    {
+        try
+        {
+            TestEngine.countIgnored++;
+            TestEngine.log("[IGNORED] " + text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logErr failure: " + err.message);
+        }
+    },
+
+    logOK: function(text)
+    {
+        try
+        {
+            TestEngine.countOK++;
+            TestEngine.log("[OK] " + text);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.logOK failure: " + err.message);
+        }
+    },
+
+    test: function(text, value)
+    {
+        try
+        {
+            if(typeof(value) == "undefined")
+            {
+                TestEngine.logErr("value not defined for test: '" + text + "'");
+            }
+            else if(!value)
+            {
+                TestEngine.logErr(text);
+            }
+            else
+            {
+                TestEngine.logOK(text);
+                return true;
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.test failure: " + err.message);
+        }
+        return false;
+    },
+
+    /**
+     * Sets error type used in every typePresetError check.
+     * @param type Type of an error/exception.
+     */
+    setErrorType: function(type)
+    {
+        TestEngine.errorType = type;
+    },
+
+    /**
+     * Sets error field used in every typePresetError check.
+     * @param field Name of the field in error structure to check its value.
+     */
+    setErrorField: function(field)
+    {
+        TestEngine.errorField = field;
+    },
+
+    /**
+     * Checks if specified expression throws a specified error.
+     * Expression must be enclosed in a function. Use setErrorType and
+     * setErrorField to set what error to look for.
+     * Error type must be set but if error field is left unset (i.e. null)
+     * then whole exception object is compared to specified value.
+     * @param msg Text to display for this test.
+     * @param fn Function eclosing the expression one wants to verify.
+     * @param value Value of an error/exception one looks for.
+     */
+    testPresetError: function(msg, fn, value)
+    {
+        if (TestEngine.errorType === null) {
+            TestEngine.logException("testPresetError skipped. Set error type first.");
+            return;
+        }
+
+        return TestEngine.testError(msg, fn, TestEngine.errorType,
+            TestEngine.errorField, value);
+    },
+
+    /**
+     * Checks if specified expression throws a specified error.
+     * This is a more general version of testPresetError function.
+     * Expression must be enclosed in a function.
+     * Error type must be set but if error field is left unset (i.e. null)
+     * then whole exception object is compared to specified value.
+     * @param msg Text to display for this test.
+     * @param fn Function eclosing the expression one wants to verify.
+     * @param errType Type of desired error/exception.
+     * @param errField Property from exception structure to look for exception
+     * value.
+     * @param errValue Value of an error/exception one looks for.
+     */
+    testError: function(msg, fn, errType, errField, errValue)
+    {
+        if (errType === null) {
+            TestEngine.logException("testError skipped. Error type can't be null.");
+            return TestEngine.ERROR_TEST_RESULT.NOT_RUN;
+        }
+
+        try {
+            fn();
+            TestEngine.logErr(msg + ' Exception has not been thrown.');
+            return TestEngine.ERROR_TEST_RESULT.NOT_THROWN;
+        }
+        catch (ex) {
+            if (ex instanceof errType) {
+                var exValue = (errField !== null ? ex[errField] : ex);
+                if (exValue === errValue) {
+                    TestEngine.logOK(msg + ' [' + errValue + ']');
+                    return TestEngine.ERROR_TEST_RESULT.OK;
+                }
+                else {
+                    TestEngine.logErr(msg + ' Exception is not of value ' + errValue);
+                    return TestEngine.ERROR_TEST_RESULT.BAD_VALUE;
+                }
+            }
+            else {
+                TestEngine.logErr(msg + ' Exception is of wrong type.');
+                return TestEngine.ERROR_TEST_RESULT.BAD_TYPE;
+            }
+        }
+    },
+
+    testPresence: function(text, object)
+    {
+        try
+        {
+            if(object === undefined)
+            {
+                TestEngine.logErr("value not defined. Name: " + text);
+            }
+            else
+            {
+                TestEngine.logOK("object " + text + " present");
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testPresence failure: " + err.message);
+        }
+    },
+
+    /**
+     * Checks whether object implements given property.
+     * In addition it also checks whether any exception (e.g. "Not Supported")
+     * is thrown.
+     * @param object Object to check property for.
+     * @param property Property to look for.
+     * @return True if object implements such property, false otherwise.
+     */
+    testPresence2: function(object, property)
+    {
+        var result = property in object;
+        if (result)
+        {
+            TestEngine.logOK("property " + property + " present");
+        }
+        else
+        {
+            TestEngine.logErr("property " + property + " absent");
+        }
+        return result;
+    },
+
+
+    /**
+     * Checks whether mainObj object equals templateObj object, property by
+     * property.
+     * Runs recursively through all the properties of templateObj object and
+     * checks if they exist and are equal to those in mainObj object.
+     * mainObj has to implement no less properties than templateObj.
+     * @param mainObj Object to check for properties implementation.
+     * @param templateObj Object to verify properties against.
+     * @return True if mainObj has at least the same properties as templateObj,
+     *         false otherwise.
+     */
+    checkObjectsEqual: function(mainObj, templateObj)
+    {
+        try
+        {
+            if ((!mainObj && templateObj) || (typeof(mainObj) != typeof(templateObj))) {
+                return false;
+            }
+            else if (isNumber(templateObj) || isString(templateObj) || isBoolean(templateObj)) {
+                return (mainObj === templateObj);
+            }
+            else if (isDate(templateObj)) {
+                return (mainObj.valueOf() === templateObj.valueOf());
+            }
+            else {
+                for (var i in templateObj) {
+                    if (!TestEngine.checkObjectsEqual(mainObj[i], templateObj[i])) {
+                        return false;
+                    }
+                }
+            }
+        }
+        catch(err)
+        {
+            TestEngine.logException("TestEngine.checkObjectsEqual failure: " + err.message);
+            return false;
+        }
+        return true;
+    },
+
+    // test properties of given object. Steps:
+    // - check name presence
+    // - check default value (if not null value passed)
+    // - check if name is writable
+    //
+    // description of properties array:
+    // [0] - property name
+    // [1] - default value - check if property equals given value
+    //          undefined or null - disable check
+    // [2] - value to do writability test - try to write given value
+    //          undefined or null - don't check writability
+    // [3] - indicates if property should be read-only
+    // [4] - assumed type, undefined value skips this check
+    testProperties: function(object, props)
+    {
+        var result = new Object();
+        try
+        {
+            for(var i in props)
+            {
+                var name = props[i][0];
+                var defaultVal = props[i][1];
+                var setVal = props[i][2];
+                var isReadonly = props[i][3];
+                var type = props[i][4];
+                var errors = TestEngine.countErr + TestEngine.countException;
+
+                if ((typeof(name) != "string") || (name == ""))
+                {
+                    TestEngine.logException("Property name not defined, skipping it.");
+                    continue;
+                }
+
+                result[name] = false;
+                if (TestEngine.testPresence2(object, name)) {
+                    if ((defaultVal != null) && (defaultVal !== undefined))
+                    {
+                        var isObjectEqual = TestEngine.checkObjectsEqual(object[name], defaultVal);
+                        TestEngine.test(name + " default value", isObjectEqual);
+                    }
+
+                    if ((setVal != null) && (setVal !== undefined))
+                    {
+                        // try-catch is needed when SetProperty returns 'false'
+                        if(setVal === defaultVal)
+                        {
+                            TestEngine.logException("Default value and set value are equal");
+                            continue;
+                        }
+                        try { object[name] = setVal; }
+                        catch (e) { }
+                        if (typeof(isReadonly) == "undefined")
+                        {
+                            TestEngine.test(name + " writability, reason: isReadonly not specified", false);
+                        }
+                        if (isReadonly)
+                        {
+                            TestEngine.test(name + " writability", object[name] != setVal);
+                        }
+                        else
+                        {
+                            var isObjectEqual = TestEngine.checkObjectsEqual(object[name], setVal);
+                            TestEngine.test(name + " writability", isObjectEqual);
+                        }
+                    }
+
+                    if (type !== undefined) {
+                        var isType = (typeof(object[name]) == typeof(type));
+                        if (typeof(type) == 'object') {
+                            if (isArray(type)) {
+                                isType = isArray(object[name]);
+                            }
+                            else if (isDate(type)) {
+                                isType = isDate(object[name]);
+                            }
+                        }
+                        TestEngine.test(name + " type check.", isType);
+                    }
+                }
+                if (errors == TestEngine.countErr + TestEngine.countException) {
+                    result[name] = true;
+                }
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testProperties failure: " + err.message);
+        }
+        return result;
+    },
+
+    startTestCase: function()
+    {
+        try
+        {
+            TestEngine.countOK = 0;
+            TestEngine.countErr = 0;
+            TestEngine.countException = 0;
+            TestEngine.countIgnored = 0;
+            TestEngine.currentFailings = [];
+            TestEngine.timer = setTimeout(TestEngine.timeout, TestEngine.currentCaseTimeout);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.startTestCase failure: " + err.message);
+        }
+
+    },
+
+    endTestCase: function(testCase)
+    {
+        try
+        {
+            if(this.timer === null)
+            {
+                return;
+            }
+
+            clearTimeout(this.timer);
+            this.log("");
+            var ignored = this.countIgnored > 0;
+            var failed = this.countErr || ((this.countOK+this.countErr)<1) || this.countException || ignored;
+
+            if (widget.__test) {
+                if (ignored) {
+                    widget.__test.collectIgnored(testCase.testName);
+                } else if (failed) {
+                    widget.__test.collectFail(testCase.testName, TestEngine.currentFailings.join('; '));
+                } else {
+                    widget.__test.collectPass(testCase.testName);
+                }
+            }
+            this.log("Test case " + (failed ? "FAILED" : "PASSED"));
+            this.log("Passed: " + this.countOK);
+            this.log("Failed: " + this.countErr);
+            if(this.countException)
+            {
+                this.log("Exception occured!");
+            }
+
+            this.countAllPassed += this.countOK;
+            this.countAllFailed += this.countErr;
+            this.testSuiteStats[testCase.testSuite].assertsOK += this.countOK;
+            this.testSuiteStats[testCase.testSuite].assertsErr += this.countErr;
+
+            if(failed)
+            {
+                TestEngine.testCasesFailedCount++;
+                this.testSuiteStats[testCase.testSuite].failed++;
+                if (isVerbose()) {
+                    TestEngine.testCasesFailed.push(testCase.testName);
+                }
+                TestEngine.resultLogger.logFail(testCase.testName);
+            }
+            else
+            {
+                TestEngine.testCasesPassedCount++;
+                this.testSuiteStats[testCase.testSuite].passed++;
+                TestEngine.resultLogger.logPass(testCase.testName);
+            }
+            TestEngine.summaryRenderer.render(TestEngine);
+        }
+        catch(err)
+        {
+            this.countException++;
+            jsPrint("   TestEngine.endTestCase failure:" + err.message);
+        }
+    },
+
+    timeout: function()
+    {
+        try
+        {
+            TestEngine.callbackMutex = 0;
+            TestEngine.logErr("Widget run timeout.", false);
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.timeout failure:" + err.message);
+        }
+    },
+
+    /**
+     * Registers callbacks for asynchronous function.
+     *
+     * To avoid finish test case before callbacks will execute it's necessary
+     * to register callbacks in the engine.
+     *
+     * @param methodName Testcase name, suggested asynchronous function name.
+     * @param testSuccessCallback Callback that will be executed on success.
+     * @param testErrorCallback Callback that will be executed on failure.
+     * @param callbacksCount number of callbacks to register.
+     * @return An object with defined functions "successCallback" and "errorCallback" you
+     *          need to pass as arguments to asynchronous function  e.g.
+     *
+     * function success() {  }
+     * function failure() {  }
+     *
+     * {
+         *      var obj = TestEngine.registerCallback("myAsyncFunc", success, failure);
+         *      myAsyncFunc(obj.successCallback, obj.errorCallback);
+         * }
+     */
+    registerCallback: function(methodName, testSuccessCallback, testErrorCallback, callbacksCount)
+    {
+        try
+        {
+            if(callbacksCount !== undefined && callbacksCount > 0){
+                TestEngine.callbackMutex += callbacksCount;
+            }
+            else {
+                TestEngine.callbackMutex++;
+            }
+            TestEngine.callbackMethodName = methodName;
+            TestEngine.testSuccessCallback = testSuccessCallback;
+            TestEngine.testErrorCallback = testErrorCallback;
+
+            var retObj = new Object();
+            retObj.callbackMethodName = methodName;
+            retObj.testSuccessCallback = testSuccessCallback;
+            retObj.successCallback = function(param){
+                try
+                {
+                    if((typeof retObj.testSuccessCallback != "undefined") && (retObj.testSuccessCallback !== null))
+                    {
+                        retObj.testSuccessCallback(param);
+                    }
+                    else
+                    {
+                        TestEngine.logOK(retObj.callbackMethodName + " succeed");
+                    }
+                }
+                catch(err)
+                {
+                    TestEngine.countException++;
+                    jsPrint("   TestEngine.this.successCallback failure:" + err.message);
+                }
+                TestEngine.callbackMutex--;
+            };
+
+            retObj.testErrorCallback = testErrorCallback;
+            retObj.errorCallback = function(param){
+                try
+                {
+                    if((typeof retObj.testErrorCallback != "undefined") && (retObj.testErrorCallback !== null))
+                    {
+                        retObj.testErrorCallback(param);
+                    }
+                    else
+                    {
+                        TestEngine.logErr(retObj.callbackMethodName + " failed");
+                    }
+                }
+                catch(err)
+                {
+                    TestEngine.countException++;
+                    jsPrint("   TestEngine.retObj.errorCallback failure:" + err.message);
+                }
+                TestEngine.callbackMutex--;
+            };
+
+            return retObj;
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.registerCallback failure:" + err.message);
+        }
+    },
+
+    successCallback: function(params)
+    {
+        TestEngine.log("[Warning] Function TestEngine.successCallback deprecated");
+        try
+        {
+            TestEngine.callbackMutex--;
+            if(typeof TestEngine.testSuccessCallback != "undefined")
+            {
+                TestEngine.testSuccessCallback(params);
+            }
+            else
+            {
+                TestEngine.logOK(TestEngine.callbackMethodName + " succeed");
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.successCallback failure:" + err.message);
+        }
+    },
+
+    errorCallback: function(params)
+    {
+        TestEngine.log("[Warning] Function TestEngine.errorCallback deprecated");
+        try
+        {
+            TestEngine.callbackMutex--;
+            if(typeof TestEngine.testErrorCallback != "undefined")
+            {
+                TestEngine.testErrorCallback(params);
+            }
+            else
+            {
+                TestEngine.logErr(TestEngine.callbackMethodName + " failed");
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.errorCallback failure:" + err.message);
+        }
+    },
+
+    waitForCallback: function()
+    {
+        try
+        {
+            //    while( TestEngine.callbackMutex )
+            {
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.waitForCallback failure:" + err.message);
+        }
+    },
+
+    /*
+     * code - error code which is expected
+     * object - object which will be used to call method
+     * functionName - method name to call
+     * restArguments - rest arguments which will be passed to callback
+     *
+     * example:
+     * TestEngine.catchError(10001, bondi.messaging, findSMSs, succCallback, null, filter)
+     */
+    catchError: function(code, object, functionName, restArguments /* , ... */ )
+    {
+        try
+        {
+            TestEngine.log("TestEngine.catchError is DEPRECATED. Please use TestEngine.catchErrorType.");
+            var error;
+            try
+            {
+                var newArgs = []
+                for (var i=3;i<arguments.length;i++) {
+                    newArgs.push(arguments[i])
+                }
+                var retVal = null;
+                retVal = object[functionName].apply(object, newArgs);
+                TestEngine.logErr(functionName + " no error thrown");
+                return retVal;
+            }
+            catch(error)
+            {
+                TestEngine.testPresence("<error code from: " + functionName + ">", error.code);
+                TestEngine.test("Error number", error.code == code);
+                return;
+            }
+            TestEngine.logErr("Function " + functionName + " desn't throw");
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testError failure:" + err.message);
+        }
+    },
+
+    /*
+     * errorTypeName - attribute name of catched exception to compare with code
+     * code - error code which is expected
+     * object - object which will be used to call method
+     * functionName - method name to call
+     * restArguments - rest arguments which will be passed to callback
+     *
+     * example:
+     * TestEngine.catchErrorType("code", 10001, bondi.messaging, findSMSs, succCallback, null, filter)
+     */
+    catchErrorType: function(errorTypeName, code, object, functionName, restArguments /* , ... */ )
+    {
+        try
+        {
+            var error;
+            try
+            {
+                var newArgs = []
+                for (var i=4;i<arguments.length;i++) {
+                    newArgs.push(arguments[i])
+                }
+                var retVal = null;
+                if (arguments.length < 4) {
+                    TestEngine.logErr("Wrong catchErrorType usage.");
+                    return retVal;
+                }
+                retVal = object[functionName].apply(object, newArgs);
+                TestEngine.logErr(functionName + " no error thrown");
+                return retVal;
+            }
+            catch(error)
+            {
+                TestEngine.testPresence("<error code from: " + functionName + ">", error[errorTypeName]);
+                TestEngine.test("Error number", error[errorTypeName] == code);
+                return;
+            }
+            TestEngine.logErr("Function " + functionName + " desn't throw");
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.testError failure:" + err.message);
+        }
+    },
+
+    // Executes step by step functions passed in steps array
+    // and waits after every execution time defined in timeInterval
+    executeSteps: function(steps, timeInterval)
+    {
+        try
+        {
+            if(typeof(timeInterval) == "undefined")
+            {
+                timeInterval = 100; //default value
+            }
+
+            TestEngine.stepsArray = steps;
+            TestEngine.stepTimeout = timeInterval;
+            TestEngine.currentStep = 0;
+            TestEngine.executeNextStep();
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.executeSteps failure:" + err.message);
+        }
+    },
+
+    executeNextStep: function()
+    {
+        try
+        {
+            if( TestEngine.stepsArray && (TestEngine.currentStep < TestEngine.stepsArray.length) )
+            {
+                if( isArray( TestEngine.stepsArray[ TestEngine.currentStep ] ) )
+                {
+                    TestEngine.stepsArray[ TestEngine.currentStep ][0]();
+                    setTimeout( TestEngine.executeNextStep, TestEngine.stepsArray[ TestEngine.currentStep ][1] );
+
+                }
+                else
+                {
+                    TestEngine.stepsArray[ TestEngine.currentStep ]();
+                    setTimeout( TestEngine.executeNextStep, TestEngine.stepTimeout );
+                }
+                TestEngine.currentStep++;
+            }
+            else
+            {
+                TestEngine.currentStep = null;
+                TestEngine.stepTimeout = null;
+                TestEngine.stepsArray = null;
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.executeNextStep failure:" + err.message);
+            jsPrint("   Current step:" + TestEngine.currentStep);
+
+            TestEngine.currentStep = null;
+            TestEngine.stepTimeout = null;
+            TestEngine.stepsArray = null;
+        }
+    },
+
+    enumerate: function(obj, level)
+    {
+        try
+        {
+            if(typeof level == "undefined")
+            {
+                TestEngine.log(obj + ":");
+                level = "";
+            }
+            for(i in obj)
+            {
+                if(!(typeof obj[i] == "object" || typeof obj[i] == "array"))
+                {
+                    TestEngine.log(level + i + " =  " + obj[i]);
+                }
+                else
+                {
+                    TestEngine.log(level + i + " =  ");
+                    TestEngine.enumerate(obj[i], level + "----");
+                }
+            }
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.enumerate failure:" + err.message);
+        }
+    },
+
+    doTests: function()
+    {
+        try
+        {
+            TestEngine.testCasesFailed = [];
+            TestEngine.test("jsPrint presence", jsPrint);
+            TestEngine.test("Widget presence", window.widget);
+            TestEngine.doNextTestCase();
+        }
+        catch(err)
+        {
+            TestEngine.countException++;
+            jsPrint("   TestEngine.doTests failure:" + err.message);
+        }
+    },
+
+    showSuitesStats: function()
+    {
+        try
+        {
+            jsPrint("============ Test suites:");
+            for(var i in this.testSuiteStats)
+            {
+                jsPrint(i + " - " + this.testSuiteStats[i].passed + " passed, " + this.testSuiteStats[i].failed + " failed," + "   asserts: " + this.testSuiteStats[i].assertsOK + " passed, " + this.testSuiteStats[i].assertsErr + " failed"); }
+        }
+        catch(err)
+        {
+            jsPrint("   TestEngine.showSuitesStats failure:" + err.message);
+        }
+    },
+
+    doNextTestCase: function()
+    {
+        try
+        {
+            if( TestEngine.stepsArray !== null || (TestEngine.callbackMutex > 0))
+            {
+                setTimeout( TestEngine.doNextTestCase, 100 );
+                return;
+            }
+
+            if(TestEngine.currentTestCase)
+            {
+                TestEngine.endTestCase(TestEngine.testList[TestEngine.currentTestCase-1]);
+            }
+
+            if( TestEngine.testList.length == TestEngine.currentTestCase )
+            {
+                if (widget.__test) {
+                    widget.__test.outputResults();
+                }
+                jsPrint("============");
+                jsPrint(TestEngine.finalLog);
+                TestEngine.showSuitesStats();
+                jsPrint("============ Summary:");
+                jsPrint("Test cases all: " + TestEngine.testList.length);
+                jsPrint("Test cases passed: " + TestEngine.testCasesPassedCount);
+                jsPrint("Test cases failed: " + TestEngine.testCasesFailedCount);
+                jsPrint("Asserts passed: " + TestEngine.countAllPassed);
+                jsPrint("Asserts failed: " + TestEngine.countAllFailed);
+                if (isVerbose()) {
+                    jsPrint("============ Failing test cases:");
+                    for (i = 0; i < TestEngine.testCasesFailed.length; ++i) {
+                        jsPrint(TestEngine.testCasesFailed[i]);
+                    }
+                }
+                TestEngine.summaryRenderer.render(TestEngine);
+
+                if(typeof TestEngine.finalCallback != "undefined")
+                {
+                    jsPrint("Registering final callback");
+                    TestEngine.summaryRenderer.render(TestEngine);
+                    setTimeout(TestEngine.finalCallback, 4000);
+                } else {
+                    jsPrint("Final callback was not registered.");
+                }
+                return;
+            }
+
+            var i = TestEngine.currentTestCase++;
+            try
+            {
+                if (widget.__test) {
+                    if (TestEngine.currentTestSuiteName != TestEngine.testList[i].testSuite) {
+                        TestEngine.currentTestSuiteName = TestEngine.testList[i].testSuite;
+                        widget.__test.collectGroup(TestEngine.testList[i].testSuite);
+                    }
+                }
+                TestEngine.log("");
+                TestEngine.log("==== Test case: " + TestEngine.testList[i].testName);
+                TestEngine.startTestCase();
+                var testPrereq = true;
+                if (TestEngine.testList[i].testPrereq !== undefined)
+                {
+                    testPrereq = TestEngine.testList[i].testPrereq();
+                }
+                if (testPrereq)
+                {
+                    if(TestEngine.testList[i].enabled)
+                    {
+                        TestEngine.testList[i].testFunc();
+                    }
+                    else
+                    {
+                        TestEngine.logIgnored("Test disabled");
+                    }
+
+                }
+                else {
+                    TestEngine.logException
+                    ("Test case prerequisites unfulfilled.  Skipping it.");
+                }
+            }
+            catch(err)
+            {
+                TestEngine.countException++;
+                TestEngine.log("   Test case '" + TestEngine.testList[i].testName + "' failed:" + err.message);
+            }
+            setTimeout( TestEngine.doNextTestCase, 100 );
+        }
+        catch(err)
+        {
+            jsPrint("   TestEngine.doNextTestCase failure:" + err.message);
+        }
+    }
+};
+
+function isUndefined(val)
+{
+    if (typeof val == "undefined") {
+        return true;
+    }
+    return false;
+}
+function isNull(val)
+{
+    return val === null;
+}
+function isString(val) {
+    if (typeof val == typeof "") {
+        return true;
+    }
+    return false;
+}
+function isNumber(val) {
+    if (typeof val == typeof 0) {
+        return true
+    }
+    return false;
+}
+function isDate(val) {
+    return (val instanceof Date);
+}
+function isFunction(val) {
+    return (typeof(val) == 'function');
+}
+function isBoolean(val) {
+    if (typeof val == typeof true) {
+        return true
+    }
+    return false;
+}
+function isArray(val) {
+    return (val instanceof Array);
+}
+function isObject(val) {
+    return (val instanceof Object);
+}
+
+function isVerbose() {
+    return ((typeof(VERBOSE) != "undefined") && (VERBOSE === 1));
+}
+
+/**
+ * Tests results logger.
+ */
+function HTMLTestResultLogger(sinkId) {
+
+  /**
+   * Logs a message.
+   * @param message Message to log.
+   * @param status Status of the message (PASSED, FAILED, EXCEPTION).
+   *               By default status is set to PASSED.
+   */
+  this.log = function(message, status) {
+    if (arguments.length < 2) throw "Not enough number of arguments.";
+    $(sink).append(createLogEntry(message, status));
+  }
+
+  /**
+   * Helper functions.
+   */
+  this.logPass = function(message) {
+    if (arguments.length < 1) throw "Not enough number of arguments.";
+    this.log(message, HTMLTestResultLogger.PASSED);
+  }
+
+  this.logFail = function(message) {
+    if (arguments.length < 1) throw "Not enough number of arguments.";
+    this.log(message, HTMLTestResultLogger.FAILED);
+  }
+
+  $(document).ready(function() {
+    sink = document.getElementById(sinkId);
+    if (null === sink) throw "Summary element unavailable.";
+  });
+
+  var createLogEntry = function(message, status) {
+    var entry = '<div class="entry ' + status + '">';
+    entry +=    message.toString();
+    entry +=    '</div>';
+    return entry;
+  }
+
+  var id = sinkId;
+  var sink = null;
+}
+
+HTMLTestResultLogger.PASSED = "passed";
+HTMLTestResultLogger.FAILED = "failed";
+HTMLTestResultLogger.EXCEPTION = "exception";
+
+
+/**
+ * Tests summary renderer.
+ */
+function HTMLTestSummaryRenderer(summaryId) {
+
+  this.render = function(engine) {
+    if (arguments.length < 1) throw "Not enough arguments.";
+
+    $('#_summary_numberOfRunTests').text(engine.currentTestCase);
+    $('#_summary_numberOfAllTests').text(engine.testList.length);
+    $('#_summary_numberOfPassedTests').text(engine.testCasesPassedCount);
+    $('#_summary_numberOfPassedAsserts').text(engine.countAllPassed);
+    $('#_summary_numberOfFailedTests').text(engine.testCasesFailedCount);
+    $('#_summary_numberOfFailedAsserts').text(engine.countAllFailed);
+    for(var suiteName in engine.testSuiteStats) {
+      if (!isSuiteStarted(engine.testSuiteStats[suiteName])) continue;
+      renderSuite(suiteName, engine.testSuiteStats[suiteName]);
+    }
+  }
+
+  $(document).ready(function() {
+    summary = document.getElementById(summaryId);
+    if (null === summary) {
+      throw "Summary element unavailable.";
+    }
+    setupSummary(summary);
+  });
+
+  var isSuiteStarted = function(stats) {
+    return (stats.passed + stats.failed != 0);
+  }
+
+  var renderSuite = function(name, stats) {
+    var elementId = '_summary_suite_' + name;
+    var element = document.getElementById(elementId);
+    if (null === element) {
+      element = $('<div id="' + elementId + '">' + name + ': '+ '<span name="stats"></span></div>');
+      $(summary).append(element);
+    }
+    var elementStats = $(element).children('span[name="stats"]');
+    elementStats.text(stats.passed + '(' + stats.assertsOK + ')' + ' passed, ' +
+                      stats.failed + '(' + stats.assertsErr + ')' + ' failed');
+  }
+
+  var setupSummary = function(summary) {
+    var run  = '<div>Run: <span id="_summary_numberOfRunTests">0</span>';
+        run += ' of <span id="_summary_numberOfAllTests">0</span></div>';
+    var current = '<div>Current: <span id="_summary_currentTest">0</span></div>';
+    var passed  = '<div>Passed: <span id="_summary_numberOfPassedTests">0</span>';
+        passed += '(<span id="_summary_numberOfPassedAsserts">0</span>)</div>';
+    var failed  = '<div>Failed: <span id="_summary_numberOfFailedTests">0</span>';
+        failed += '(<span id="_summary_numberOfFailedAsserts">0</span>)</div>';
+    $(summary).append(run).append(passed).append(failed);
+  }
+
+  var id = summaryId;
+  var summary = null;
+}
+
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/CloseCallback.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/CloseCallback.js
new file mode 100644 (file)
index 0000000..102e865
--- /dev/null
@@ -0,0 +1 @@
+TestEngine.setFinalCallback(function(){ jsPrint("closing window"); window.close(); });
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestAccelerometer.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestAccelerometer.js
new file mode 100644 (file)
index 0000000..d3dd9f0
--- /dev/null
@@ -0,0 +1,154 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test Accelerometer class.
+ *
+ * @author      xiangguo.qi (xiangguo.qi @samsung.com)
+ * @version     0.1
+ */
+
+
+var AccelerometerObj = deviceapis.accelerometer;
+var WatchID = "";
+// Accelerometer001
+function presenceTest()
+{
+    TestEngine.test("Checking checking", true);
+    TestEngine.test("Checking deviceapis object", deviceapis);
+    TestEngine.test("Checking Accelerometer object", AccelerometerObj);
+
+    TestEngine.test("Checking type of getCurrentAcceleration", isFunction(AccelerometerObj.getCurrentAcceleration));
+    TestEngine.test("Checking type of watchAcceleration", isFunction(AccelerometerObj.watchAcceleration));
+    TestEngine.test("Checking type of clearWatch", isFunction(AccelerometerObj.clearWatch));
+}
+
+// Accelerometer002
+function getCurrentAccelerationInvalidParamsTest()
+{
+    // Following two tests should silently fail according to WAC 2.0
+    TestEngine.test("getCurrentAcceleration undefined callback", isUndefined(AccelerometerObj.getCurrentAcceleration(undefined)));
+    TestEngine.test("getCurrentAcceleration null callback", isUndefined(AccelerometerObj.getCurrentAcceleration(null)));
+    // Following tests should throw errors according to WAC 2.0
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "getCurrentAcceleration", "test");
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "getCurrentAcceleration", new Date());
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "getCurrentAcceleration", [6, 6, 6]);
+}
+
+
+// Accelerometer003
+function getCurrentAccelerationTest()
+{
+    getCurrentAccelerationCheck();
+}
+
+function getCurrentAccelerationCheck()
+{
+       function getSuccess(acceleration) {
+        TestEngine.test("getCurrentAccleration success - error expected", false);
+//      TestEngine.test("get current acceleration",true);
+//      TestEngine.test("acceleration.xAxis", isNumber(acceleration.xAxis));
+//      TestEngine.test("acceleration.yAxis", isNumber(acceleration.yAxis));
+//         TestEngine.test("acceleration.zAxis", isNumber(acceleration.zAxis));
+    }
+
+    function getFail() {
+        TestEngine.test("getCurrentAcceleration failed as expected", true);
+//        TestEngine.test("get current acceleration",false);
+    }
+
+    var cbObj = TestEngine.registerCallback("getCurrentAcceleration", getSuccess, getFail);
+    AccelerometerObj.getCurrentAcceleration(cbObj.successCallback, cbObj.errorCallback);
+
+}
+
+// Accelerometer004
+function watchAccelerationInvalidParamsTest()
+{
+    // Following two tests should silently fail according to WAC 2.0
+    TestEngine.test("watchAcceleration undefined callback", isUndefined(AccelerometerObj.watchAcceleration(undefined)));
+    TestEngine.test("watchAcceleration null callback", isUndefined(AccelerometerObj.watchAcceleration(null)));
+    // Following tests should throw errors according to WAC 2.0
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "watchAcceleration", "test");
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "watchAcceleration", new Date());
+    TestEngine.catchErrorType("code",17, AccelerometerObj, "watchAcceleration", [6, 6, 6]);
+    // Following tests should ignore optional parameter if it is of invalid type, according to WAC 2.0
+    TestEngine.test("watchAcceleration ignore invalid params", isNumber(AccelerometerObj.watchAcceleration(function(){}, function(){}, "test")));
+    TestEngine.test("watchAcceleration ignore invalid params", isNumber(AccelerometerObj.watchAcceleration(function(){}, function(){}, {minNotificationInterval:"test"})));
+    TestEngine.test("watchAcceleration ignore invalid params", isNumber(AccelerometerObj.watchAcceleration(function(){}, function(){}, {minNotificationInterval:true})));
+}
+
+
+// Accelerometer005
+function watchAccelerationTest()
+{
+    watchAccelerationCheck();
+}
+
+function watchAccelerationCheck()
+{
+       function watchSuccess(acceleration) {
+        TestEngine.test("watch acceleration",true);
+               TestEngine.test("acceleration.xAxis", isNumber(acceleration.xAxis));
+               TestEngine.test("acceleration.yAxis", isNumber(acceleration.yAxis));
+               TestEngine.test("acceleration.zAxis", isNumber(acceleration.zAxis));
+
+    }
+
+    function watchFail() {
+        TestEngine.test("watch acceleration",false);
+    }
+
+    var cbObj = TestEngine.registerCallback("watchAcceleration", watchSuccess, watchFail);
+    WatchID = AccelerometerObj.watchAcceleration(cbObj.successCallback, cbObj.errorCallback, {minNotificationInterval:2000});
+
+}
+
+// Accelerometer006
+function clearWatchTest()
+{
+    var ids = [WatchID, null, new Date(), true, undefined, "test", [6, 6, 6]];
+    for (var i =0; i < ids.length; ++i) {
+        try
+        {
+            AccelerometerObj.clearWatch(ids[i]);
+            TestEngine.logOK("clearWatch OK");
+        }
+        catch (error) {
+            TestEngine.logErr("clearWatch Error");
+        }
+    }
+
+    try
+    {
+        AccelerometerObj.clearWatch();
+        TestEngine.logOK("clearWatch OK");
+    }
+    catch (error) {
+        TestEngine.logErr("clearWatch Error");
+    }
+}
+
+
+//=============================================================================
+
+TestEngine.setTestSuiteName("[WAC2.0][Accelerometer]", 60*1000); //2min time out for callbacks
+//TestEngine.addTest(true, presenceTest, "[WAC2.0][Accelerometer] Accelerometer functions presence test");
+//TestEngine.addTest(true, getCurrentAccelerationInvalidParamsTest, "[WAC2.0][Accelerometer] getCurrentAcceleration invalid params  test");
+TestEngine.addTest(true, getCurrentAccelerationTest, "[WAC2.0][Accelerometer] getCurrentAcceleration test");
+//TestEngine.addTest(true, watchAccelerationInvalidParamsTest, "[WAC2.0][Accelerometer] watchAcceleration invalid params  test");
+//TestEngine.addTest(true, watchAccelerationTest, "[WAC2.0][Accelerometer] watchtAcceleration test");
+//TestEngine.addTest(true, clearWatchTest, "[WAC2.0][Accelerometer] clearWatch test");
+
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestCalendar.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestCalendar.js
new file mode 100644 (file)
index 0000000..ec3c00d
--- /dev/null
@@ -0,0 +1,1577 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test calendar class.
+ *
+ * @author      Lukasz Marek (l.marek@samsung.com)
+ * @version     0.1
+ */
+
+var TYPE_MISMATCH_ERR = 17;
+var INVALID_VALUES_ERR = 22;
+var NOT_FOUND_ERR = 8;
+
+var TestCalendar = {
+    calendar: null,
+    event:null,
+    old_event:null,
+    num_events:null,
+    found_events:null,
+    all_events:null,
+    expectedErrorCode: null,
+
+    createTestEvent: function (response)
+    {
+        return TestCalendar.calendar.createEvent({description:'Test Event 1',
+                summary:'Event created to test event creation',
+                startTime: new Date(2009, 3, 30, 10, 0),
+                duration : 60,
+                location:'London',
+                recurrence:0});
+    },
+
+    onSuccessNonExpected: function(response)
+    {
+        TestEngine.test("non expected successCallback invoked", false);
+    },
+
+    onErrorExpected: function(response)
+    {
+        TestEngine.test("expected errorCallback invoked", true);
+        TestEngine.testPresence("error code", response.code);
+        TestEngine.test("Error number", response.code == TestCalendar.expectedErrorCode);
+    },
+
+    onSuccess: function(response)
+    {
+        TestEngine.test("Callback success", true);
+    },
+
+    onErrorCb: function(response)
+    {
+        TestEngine.logErr("errorCallback invoked [" + response.code + ']');
+    },
+
+    //Cal001
+    test_modulePresence: function()
+    {
+        TestEngine.test("Calendar manager presence", deviceapis.pim.calendar);
+    },
+    //Cal002
+    test_calendarManagerConstants: function()
+    {
+        TestEngine.test("test property SIM_CALENDAR", deviceapis.pim.calendar.SIM_CALENDAR === 0);
+        TestEngine.test("test property DEVICE_CALENDAR", deviceapis.pim.calendar.DEVICE_CALENDAR === 1);
+        TestEngine.test("test property NO RECURRENCE", deviceapis.pim.calendar.NO_RECURRENCE === 0);
+        TestEngine.test("test property DAILY RECURENCE", deviceapis.pim.calendar.DAILY_RECURRENCE === 1);
+        TestEngine.test("test property WEEKLY RECURRENCE", deviceapis.pim.calendar.WEEKLY_RECURRENCE === 2);
+        TestEngine.test("test property MONTHLY RECURRENCE", deviceapis.pim.calendar.MONTHLY_RECURRENCE === 3);
+        TestEngine.test("test property YEARLY_RECURRENCE", deviceapis.pim.calendar.YEARLY_RECURRENCE === 4);
+        TestEngine.test("test property TENTATIVE_STATUS", deviceapis.pim.calendar.TENTATIVE_STATUS === 0);
+        TestEngine.test("test property CONFIRMED STATUS", deviceapis.pim.calendar.CONFIRMED_STATUS === 1);
+        TestEngine.test("test property CANCELED STATUS", deviceapis.pim.calendar.CANCELLED_STATUS === 2);
+        TestEngine.test("test property ALARM", deviceapis.pim.calendar.NO_ALARM === 0);
+        TestEngine.test("test property SILENT_ALARM", deviceapis.pim.calendar.SILENT_ALARM === 1);
+        TestEngine.test("test property SOUND_ALARM", deviceapis.pim.calendar.SOUND_ALARM === 2);
+    },
+
+    //Cal003
+    test_getCalendar: function()
+    {
+        function onSuccessGetCalendar(response)
+        {
+            TestEngine.test("Found calendars - it should fail.", false);
+            TestCalendar.calendar=response[0];
+        }
+        function onErrorCb(response)
+        {
+            TestEngine.test("getCalendars error callback - as expected", true);
+            TestEngine.log("error callback invoked with code " +response.code);
+        }
+
+        var cbObj = TestEngine.registerCallback("getCalendars",
+            onSuccessGetCalendar,
+            onErrorCb);
+        deviceapis.pim.calendar.getCalendars(cbObj.successCallback, cbObj.errorCallback);
+    },
+
+    //Cal004
+    test_getCalendarNoCallbacks: function()
+    {
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(null);
+            }
+        );
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(undefined);
+            }
+        );
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(null, null);
+            }
+        );
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(undefined, undefined);
+            }
+        );
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(null, undefined);
+            }
+        );
+        testNoExceptionWithMessage("getCalendars() missing error callback",
+            function()
+            {
+                deviceapis.pim.calendar.getCalendars(undefined, null);
+            }
+        );
+    },
+
+    //Cal005
+    test_getCalendarInvalidCallbacks: function()
+    {
+        function onError(error)
+        {
+            TestEngine.test("getCalendars()", (error.code == INVALID_VALUES_ERR));
+        }
+        function onUnexpectedCallback()
+        {
+            TestEngine.test("getCalendars() unexpected callback", false);
+        }
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars");
+
+        var cbObj = TestEngine.registerCallback("getCalendars", null, onError);
+        deviceapis.pim.calendar.getCalendars(null, cbObj.errorCallback);
+
+        cbObj = TestEngine.registerCallback("getCalendars", null, onError);
+        deviceapis.pim.calendar.getCalendars(undefined, cbObj.errorCallback);
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", onUnexpectedCallback, 2);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", onUnexpectedCallback, "test2");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", 2, onUnexpectedCallback);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", "test2", onUnexpectedCallback);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", 2, null);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", "test2", undefined);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", 2);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, deviceapis.pim.calendar, "getCalendars", "test2");
+    },
+
+    //Cal006
+    test_calendarMethodsPresence: function()
+    {
+        TestEngine.testPresence("calendar.createEvent presence", TestCalendar.calendar.createEvent);
+        TestEngine.testPresence("calendar.addEvent presence", TestCalendar.calendar.addEvent);
+        TestEngine.testPresence("calendar.updateEvent presence", TestCalendar.calendar.updateEvent);
+        TestEngine.testPresence("calendar.deleteEvent presence", TestCalendar.calendar.deleteEvent);
+        TestEngine.testPresence("calendar.findEvents presence", TestCalendar.calendar.findEvents);
+    },
+
+    //Cal007
+    test_getCalendarName: function()
+    {
+        var cName = TestCalendar.calendar.name;
+        TestEngine.test("test getName", isString(cName) && cName.length > 0);
+        TestEngine.log("calendar name: " + cName);
+    },
+
+    //Cal008
+    test_getCalendarType: function ()
+    {
+        var cType = TestCalendar.calendar.type;
+        TestEngine.test("test getType", cType === deviceapis.pim.calendar.SIM_CALENDAR ||
+                                        cType === deviceapis.pim.calendar.DEVICE_CALENDAR);
+        TestEngine.log("calendar type: " + cType);
+
+    },
+
+    //Cal009
+    test_createEmptyEvent: function()
+    {
+        var event = TestCalendar.calendar.createEvent();
+        TestEngine.test("event created", isObject(event));
+    },
+
+    //Cal010
+    test_eventAttributes: function()
+    {
+        var event = TestCalendar.calendar.createEvent();
+        TestEngine.test("test attribute id", isString(event.id) || isNull(event.id) || isUndefineD(event.id));
+        var oldId = event.id;
+        event.id = "test" + oldId;
+        TestEngine.test("attribute id is read only", event.id === oldId);
+        TestEngine.test("test attribute description", isString(event.description));
+        TestEngine.test("test attribute summary", isString(event.summary));
+        TestEngine.test("test attribute startTime", isDate(event.startTime));
+        TestEngine.test("test attribute duration", isNumber(event.duration));
+        TestEngine.test("test attribute location", isString(event.location));
+        TestEngine.test("test attribute categories", isObject(event.categories) && event.categories.length == 0);
+        TestEngine.test("test attribute recurrence", isNumber(event.recurrence) && event.recurrence === deviceapis.pim.calendar.NO_RECURRENCE);
+        TestEngine.test("test attribute expires", event.expires === null);
+        TestEngine.test("test attribute interval", isNumber(event.interval));
+        TestEngine.test("test attribute status", isNumber(event.status) && event.status === deviceapis.pim.calendar.CONFIRMED_STATUS);
+        TestEngine.test("test attribute alarmTrigger", isNumber(event.alarmTrigger) && event.alarmTrigger === 0);
+        TestEngine.test("test attribute alarmType", isNumber(event.alarmType) && event.alarmType === deviceapis.pim.calendar.NO_ALARM);
+    },
+
+    //Cal011
+    test_createEvent: function()
+    {
+        var eventProp = {
+                description: 'Event created to test event creation',
+                summary: 'Test Event 1',
+                startTime: new Date(2009, 3, 30, 10, 0),
+                duration: 60,
+                location: 'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.DAILY_RECURRENCE,
+                expires: new Date(2009, 4, 30, 10, 0),
+                interval: 2,
+                status: deviceapis.pim.calendar.CANCELLED_STATUS,
+                alarmTrigger: -5,
+                alarmType: deviceapis.pim.calendar.SILENT_ALARM
+            };
+
+        var newEvent = TestCalendar.calendar.createEvent(eventProp);
+
+        TestEngine.test("event with param created ", newEvent);
+        TestEngine.test("correct description", newEvent.description === eventProp.description);
+        TestEngine.test("correct summary", newEvent.summary === eventProp.summary);
+        TestEngine.test("correct startTime", newEvent.startTime.toString() === eventProp.startTime.toString());
+        TestEngine.test("correct duration", newEvent.duration === eventProp.duration);
+        TestEngine.test("correct location", newEvent.location === eventProp.location);
+        TestEngine.test("correct categories", newEvent.categories.length === eventProp.categories.length &&
+                                              newEvent.categories[0] === eventProp.categories[0]);
+        TestEngine.test("correct recurrence", newEvent.recurrence === eventProp.recurrence);
+        TestEngine.test("correct expires", newEvent.expires.toString() === eventProp.expires.toString());
+        TestEngine.test("correct interval", newEvent.interval === eventProp.interval);
+        TestEngine.test("correct status", newEvent.status === eventProp.status);
+        TestEngine.test("correct alarmTrigger", newEvent.alarmTrigger === eventProp.alarmTrigger);
+        TestEngine.test("correct alarmType", newEvent.alarmType === eventProp.alarmType);
+
+    },
+
+    //this function is called from test_addEvent1, test_addEvent2 ...
+    addEvent: function(newEvent)
+    {
+        var event = newEvent;
+        var num_events;
+
+        function onErrorCb(response)
+        {
+            TestEngine.logErr("errorCallback invoked [" + response.code + ']');
+            TestEngine.test("add event", false);
+        }
+
+        function onSuccessAddEventCountAfter(response)
+        {
+            TestEngine.log("There is " + response.length +" events");
+            TestEngine.log("added event's id " + event.id);
+            TestEngine.test("Number of events increased", num_events + 1 == response.length);
+            var eventValidated = false;
+            for (var i in response) {
+                if (event.id != response[i].id) {
+                    continue;
+                }
+                TestEngine.test("description the same", response[i].description === event.description);
+                TestEngine.test("summary the same", response[i].summary === event.summary);
+                TestEngine.test("startTime the same", response[i].startTime.toString() === event.startTime.toString());
+                TestEngine.test("duration the same", response[i].duration === event.duration);
+                TestEngine.test("location the same", response[i].location === event.location);
+                TestEngine.test("categories the same", response[i].categories.length === event.categories.length);
+                TestEngine.test("recurrence the same", response[i].recurrence === event.recurrence);
+                TestEngine.test("expires the same", isNull(event.expires) ||
+                                                    response[i].expires.toString() === event.expires.toString());
+                TestEngine.test("interval the same", response[i].interval === event.interval);
+                TestEngine.test("status the same", response[i].status === event.status);
+                TestEngine.test("alarmTrigger the same, " + response[i].alarmTrigger, response[i].alarmTrigger === event.alarmTrigger);
+                TestEngine.test("alarmType the same", response[i].alarmType === event.alarmType);
+                eventValidated = true;
+            }
+            TestEngine.test("Event has been validated", eventValidated)
+            num_events=null;
+        }
+
+        function onSuccessAddEventAdd(response)
+        {
+            TestEngine.log("event added");
+            //count the number of events
+            TestEngine.log("counting existing events");
+            var objCb = TestEngine.registerCallback("onSuccessAddEventAdd",
+                onSuccessAddEventCountAfter, onErrorCb);
+            TestCalendar.calendar.findEvents(objCb.successCallback,
+                objCb.errorCallback);
+        }
+
+        function onSuccessAddEventCountBefore(response)
+        {
+            TestEngine.log("events counted");
+            //save current number of events
+            num_events = response.length;
+            TestEngine.log("There is " + num_events +" events");
+            TestEngine.log("adding new event");
+            //add new event
+            var objCb = TestEngine.registerCallback("onSuccessAddEventCountBefore",
+                onSuccessAddEventAdd, onErrorCb);
+            TestCalendar.calendar.addEvent(objCb.successCallback,
+                objCb.errorCallback,
+                event);
+        }
+
+        //save current number of events
+        TestEngine.log("counting existing events");
+        var objCb = TestEngine.registerCallback("findEvents",
+            onSuccessAddEventCountBefore,
+            onErrorCb);
+        TestCalendar.calendar.findEvents(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal012
+    test_addEvent1: function()
+    {
+        TestEngine.log("creating new event");
+        var event = TestCalendar.calendar.createEvent();
+        TestEngine.log("new event created");
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal013
+    test_addEvent2: function()
+    {
+        TestEngine.log("creating new event");
+        var event = TestCalendar.calendar.createEvent({
+                description:'Event created to test event creation',
+                summary:'Test Event 2',
+                startTime: new Date(2010, 11, 30, 10, 0),
+                duration: 15,
+                location:'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.DAILY_RECURRENCE,
+                expires: null,
+                interval: 1,
+                status: deviceapis.pim.calendar.TENTATIVE_STATUS,
+                alarmTrigger: 10,
+                alarmType: deviceapis.pim.calendar.SILENT_ALARM
+            });
+        TestEngine.log("new event created");
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal014
+    test_addEvent3: function()
+    {
+        TestEngine.log("creating new event");
+        var event = TestCalendar.calendar.createEvent({
+                description:'Event created to test event creation',
+                summary:'Test Event 3',
+                startTime: new Date(2010, 11, 30, 10, 0),
+                duration: 2,
+                location:'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.WEEKLY_RECURRENCE,
+                expires: new Date(2011, 11, 30, 10, 0),
+                interval: 1,
+                status: deviceapis.pim.calendar.CANCELLED_STATUS,
+                alarmTrigger: 0,
+                alarmType: deviceapis.pim.calendar.SOUND_ALARM
+            });
+        TestEngine.log("new event created");
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal015
+    test_addEvent4: function()
+    {
+        var event = TestCalendar.calendar.createEvent({
+                description:'Event created to test event creation',
+                summary:'Test Event 4',
+                startTime: new Date(2010, 11, 30, 10, 0),
+                duration: 60,
+                location:'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.NO_RECURRENCE,
+                expires: null,
+                interval: 1,
+                status: deviceapis.pim.calendar.CONFIRMED_STATUS,
+                alarmTrigger: -15,
+                alarmType: deviceapis.pim.calendar.NO_ALARM
+            });
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal016
+    test_addEvent5: function()
+    {
+        var event = TestCalendar.calendar.createEvent({
+                description:'Event created to test event creation',
+                summary:'Test Event 5',
+                startTime: new Date(2010, 11, 30, 10, 0),
+                duration: 60,
+                location:'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.MONTHLY_RECURRENCE,
+                expires: null,
+                interval: 1,
+                status: deviceapis.pim.calendar.CONFIRMED_STATUS,
+                alarmTrigger: -15,
+                alarmType: deviceapis.pim.calendar.NO_ALARM
+            });
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal017
+    test_addEvent6: function()
+    {
+        var event = TestCalendar.calendar.createEvent({
+                description:'Event created to test event creation',
+                summary:'Test Event 6',
+                startTime: new Date(2010, 11, 30, 10, 0),
+                duration: 60,
+                location:'London',
+                categories: ["SPRC"],
+                recurrence: deviceapis.pim.calendar.YEARLY_RECURRENCE,
+                expires: null,
+                interval: 1,
+                status: deviceapis.pim.calendar.CONFIRMED_STATUS,
+                alarmTrigger: -15,
+                alarmType: deviceapis.pim.calendar.NO_ALARM
+            });
+        TestCalendar.addEvent(event);
+    },
+
+    //Cal019
+    test_addEventNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent");
+    },
+
+    //Cal020
+    test_addEventInvalidCallbacksParams: function()
+    {
+        function onError(error)
+        {
+            TestEngine.test("addEvent()", (error.code == INVALID_VALUES_ERR));
+        }
+        function onUnexpectedCallback()
+        {
+            TestEngine.test("addEvent() unexpected callback", false);
+        }
+
+        var event = TestCalendar.createTestEvent();
+
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, undefined, event);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, undefined, event);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, null, event);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, null, event);
+        });
+
+        var cbObj = TestEngine.registerCallback("addEvent()", null, onError);
+        deviceapis.pim.calendar.getCalendars(null, cbObj.errorCallback, event);
+
+        cbObj = TestEngine.registerCallback("addEvent()", null, onError);
+        deviceapis.pim.calendar.getCalendars(undefined, cbObj.errorCallback, event);
+
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, undefined, null);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, undefined, undefined);
+        });
+
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, null, null);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, null, undefined);
+        });
+
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, undefined, null);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(null, undefined, undefined);
+        });
+
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, null, null);
+        });
+        testNoExceptionWithMessage("addEvent()", function() {
+            TestCalendar.calendar.addEvent(undefined, null, undefined);
+        });
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", 1, 1, null);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", "test", "test", null);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", 1, 1, undefined);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", "test", "test", undefined);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", 1, 1, event);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent", "test", "test", event);
+    },
+
+    //Cal021
+    test_addEventWrongEventParam: function()
+    {
+        function onError(error)
+        {
+            TestEngine.test("addEvent()", (error.code == INVALID_VALUES_ERR));
+        }
+
+        function onSuccessNonExpected()
+        {
+            TestEngine.test("addEvent() non expected successCallback invoked", false);
+        }
+
+        function onUnexpectedCallback()
+        {
+            TestEngine.test("addEvent() unexpected callback", false);
+        }
+
+        var cbObj = TestEngine.registerCallback("addEvent()", onSuccessNonExpected, onError);
+        TestCalendar.calendar.addEvent(cbObj.successCallback, cbObj.errorCallback, null);
+
+        cbObj = TestEngine.registerCallback("addEvent()", onSuccessNonExpected, onError);
+        TestCalendar.calendar.addEvent(cbObj.successCallback, cbObj.errorCallback, undefined);
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent",
+            onUnexpectedCallback, onUnexpectedCallback, 22);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent",
+            onUnexpectedCallback, onUnexpectedCallback, "test");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent",
+            onUnexpectedCallback, onUnexpectedCallback);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "addEvent",
+            onUnexpectedCallback, onUnexpectedCallback, new Date());
+    },
+
+    //Cal022
+    test_findAllEvents: function()
+    {
+        function onSuccessFindAllEvents(response)
+        {
+            TestEngine.test("Find all events", response.length > 0);
+        }
+
+        function onErrorCb()
+        {
+            TestEngine.test("Find all events", false);
+        }
+
+        var objCb = TestEngine.registerCallback("findEvents",
+            onSuccessFindAllEvents,
+            onErrorCb);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    //function called by following tests
+    test_FindEventsWithFilterSomeResults: function(filterEval)
+    {
+        function onSuccessFindAllEvents(response)
+        {
+            function onSuccessFindEventWithFilterSomeResults(response)
+            {
+                TestEngine.log("found events: " + response.length);
+                TestEngine.test("FindEvents with filter found results", response.length > 0);
+            }
+
+            function onErrorCb()
+            {
+                TestEngine.test("FindEvents error callback", false);
+            }
+
+            TestEngine.test("Found any event for tests", response.length > 0);
+            if (response.length > 0) {
+                eval(filterEval);
+                if (filter) {
+                    for(var i in filter) {
+                        TestEngine.log("  Filter: " + i + " : " + filter[i]);
+                    }
+                }
+                var objCb = TestEngine.registerCallback("findEvents",
+                    onSuccessFindEventWithFilterSomeResults,
+                    onErrorCb);
+                TestCalendar.calendar.findEvents(objCb.successCallback,
+                    objCb.errorCallback,
+                    filter);
+            }
+        }
+
+        function onErrorCb()
+        {
+            TestEngine.test("Find all events", false);
+        }
+
+        var objCb = TestEngine.registerCallback("findEvents",
+            onSuccessFindAllEvents,
+            onErrorCb);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback);
+        },
+
+    //Cal023
+    test_findEventsId: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {id: response[0].id}");
+    },
+
+    //Cal024
+    test_findEventsSummary: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {summary: response[0].summary}");
+    },
+
+    //Cal025
+    test_findEventsDescription: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {description: response[0].description}");
+    },
+
+    //Cal026
+    test_findEventsLocation: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {location: response[0].location}");
+    },
+
+    //Cal027
+    test_findEventsCategory: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {category: 'SPRC'}");
+    },
+
+    //Cal028
+    test_findEventsStatus: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {status: [response[0].status]}");
+    },
+
+    //Cal029
+    test_findEventsFullStartTime: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {initialStartDate: response[0].startTime, endStartDate: response[0].startTime}");
+    },
+
+    //Cal030
+    test_findEventsInitialStartDate: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {initialStartDate: response[0].startTime, endStartDate: null}");
+    },
+
+    //Cal031
+    test_findEventsEndStartDate: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults(
+            "var filter = {initialStartDate: null, endStartDate: response[0].startTime}");
+    },
+
+    //Cal032
+    test_findEventsEmptyFilter: function()
+    {
+        TestCalendar.test_FindEventsWithFilterSomeResults("var filter = {}");
+    },
+
+    //function called by following tests
+    test_FindEventsWithFilterNoResults: function(filter)
+    {
+        function onSuccessFindEventWithFilterNoResults(response)
+        {
+            TestEngine.test("FindEvents with filter not found results", response.length == 0);
+        }
+
+        function onErrorCb()
+        {
+            TestEngine.test("FindEvents error callback", false);
+        }
+
+        if(filter) {
+            for(var i in filter) {
+                TestEngine.log("  Filter: " + i + " : " + filter[i]);
+            }
+        }
+        var objCb = TestEngine.registerCallback("findEvents",
+            onSuccessFindEventWithFilterNoResults,
+            onErrorCb);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback,
+            filter);
+    },
+
+    //Cal033
+    test_findEventsFullStartTimeNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {initialStartDate: new Date(1980, 11, 30, 1, 0),
+             endStartDate: new Date(1980, 11, 30, 23, 0)});
+    },
+
+    //Cal034
+    test_findEventsLocationNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {location:"non existing location"});
+    },
+
+    //Cal035
+    test_findEventsSummaryNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {summary:'non existing summary'});
+    },
+
+    //Cal036
+    test_findEventsDescriptionNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {description:'non existing description'});
+    },
+
+    //Cal037
+    test_findEventsIdNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {id:"2000000"});
+    },
+
+    //Cal038
+    test_findEventsCategoryNoResults: function()
+    {
+        TestCalendar.test_FindEventsWithFilterNoResults(
+            {category:'non existing category'});
+    },
+
+    //Cal039
+    test_findEventsNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "findEvents");
+    },
+
+    //Cal040
+    test_findEventsNoCallbacksParams: function()
+    {
+        testNoExceptionWithMessage("findEvents() null callbacks",
+            function()
+            {
+                TestCalendar.calendar.findEvents(null, null);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() undefined callbacks",
+            function()
+            {
+                TestCalendar.calendar.findEvents(undefined, undefined);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() undefined success callback, null error callback",
+            function()
+            {
+                TestCalendar.calendar.findEvents(undefined, null);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() null success callback, undefined error callback",
+            function()
+            {
+                TestCalendar.calendar.findEvents(null, undefined);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() undefined success callback, missing error callback",
+            function()
+            {
+                TestCalendar.calendar.findEvents(undefined);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() null success callback, missing error callback",
+            function()
+            {
+                TestCalendar.calendar.findEvents(null);
+            }
+        );
+        testNoExceptionWithMessage("findEvents() null callbacks, empty filter",
+            function()
+            {
+                TestCalendar.calendar.findEvents(null, null, {});
+            }
+        );
+        testNoExceptionWithMessage("findEvents() undefined callbacks, empty filter",
+            function()
+            {
+                TestCalendar.calendar.findEvents(undefined, undefined, {});
+            }
+        );
+    },
+
+    //Cal041
+    test_findEventsWrongFilterParam: function()
+    {
+        function onSuccess(response)
+        {
+            TestEngine.test("findEvents() success callback invoked", true);
+        }
+
+        function onError(response)
+        {
+            TestEngine.test("findEvents() error callback invoked", false);
+        }
+
+        var objCb = TestEngine.registerCallback("Find events with undefined filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback, null);
+
+        objCb = TestEngine.registerCallback("Find events with undefined filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback, undefined);
+    },
+
+    //this function is called by following tests
+    updateEvent: function(newValues)
+    {
+        function onErrorCb()
+        {
+            TestEngine.test("Find all events", false);
+        }
+
+        function onSuccessFindAllEvents(response)
+        {
+            TestEngine.test("Find all events", response.length > 0);
+            if (response.length > 0) {
+                var event = response[0];
+                function onSuccessUpdateEvent1(response)
+                {
+                    TestEngine.log("updateEvent() success callback entered entered");
+
+                    function onSuccessUpdateEvent2(response)
+                    {
+                        TestEngine.test("found updated event", response.length > 0);
+                        if (response.length > 0) {
+                            var f_flag = 0;
+                            for (var i in response) {
+                                f_flag = 1;
+                                for (var j in newValues) {
+                                    if (isDate(newValues[j])) {
+                                        if (response[i][j].toString() != newValues[j].toString()) {
+                                            f_flag = 0;
+                                            break;
+                                        }
+                                    }
+                                    else if (isArray(newValues[j]))
+                                    {
+                                        if (response[i][j].length != newValues[j].length ||
+                                            response[i][j][0] != newValues[j][0]) {
+                                            f_flag = 0;
+                                            break;
+                                        }
+                                    }
+                                    else {
+                                        if (response[i][j] !== newValues[j]) {
+                                            if (j == "expires" && newValues[j] == null) {
+                                                //expires date with null should not be checked
+                                                TestEngine.log("dupa " + j);
+                                                continue;
+                                            }
+                                            f_flag = 0;
+                                            break;
+                                        }
+                                    }
+                                }
+                                if (f_flag == 1) {
+                                    break;
+                                }
+                            }
+                            TestEngine.test("Updated event validated successfully", f_flag == 1);
+                        }
+                        else {
+                            TestEngine.test("Updated events found", false);
+                        }
+                    }
+
+                    //find updated event
+                    var objCb = TestEngine.registerCallback("findEvents",
+                        onSuccessUpdateEvent2,
+                        onErrorCb);
+                    TestCalendar.calendar.findEvents(objCb.successCallback,
+                        objCb.errorCallback, {id: event.id});
+                }
+                for (var i in newValues) {
+                    TestEngine.log("update property: " + i + ", new value: " + newValues[i]);
+                    event[i] = newValues[i];
+                }
+                var objCb = TestEngine.registerCallback("updateEvent",
+                    onSuccessUpdateEvent1,
+                    onErrorCb);
+                TestCalendar.calendar.updateEvent(objCb.successCallback,
+                    objCb.errorCallback,
+                    event);
+            }
+        }
+
+        var objCb = TestEngine.registerCallback("findEvents",
+            onSuccessFindAllEvents,
+            onErrorCb);
+        TestCalendar.calendar.findEvents(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    //Cal042
+    test_updateEvent1: function()
+    {
+        var newValues = {
+                description:'updated description 1',
+                summary:'Updated Test Event 1',
+                startTime: new Date(2011, 01, 01, 01, 01),
+                duration: 11,
+                location:'London 1',
+                categories: ["SPRC 1"],
+                recurrence: deviceapis.pim.calendar.NO_RECURRENCE,
+                expires: null,
+                interval: 1,
+                status: deviceapis.pim.calendar.TENTATIVE_STATUS,
+                alarmTrigger: 1,
+                alarmType: deviceapis.pim.calendar.NO_ALARM
+            };
+        TestCalendar.updateEvent(newValues)
+    },
+
+    //Cal043
+    test_updateEvent2: function()
+    {
+        var newValues = {
+                description:'updated description 2',
+                summary:'Updated Test Event 2',
+                startTime: new Date(2012, 02, 02, 02, 02),
+                duration: 22,
+                location:'London 2',
+                categories: ["SPRC 2"],
+                recurrence: deviceapis.pim.calendar.DAILY_RECURRENCE,
+                expires: null,
+                interval: 2,
+                status: deviceapis.pim.calendar.CONFIRMED_STATUS,
+                alarmTrigger: 2,
+                alarmType: deviceapis.pim.calendar.SILENT_ALARM
+            };
+        TestCalendar.updateEvent(newValues)
+    },
+
+    //Cal044
+    test_updateEvent3: function()
+    {
+        var newValues = {
+                description:'updated description 3',
+                summary:'Updated Test Event 3',
+                startTime: new Date(2013, 03, 03, 03, 03),
+                duration: 33,
+                location:'London 3',
+                categories: [],
+                recurrence: deviceapis.pim.calendar.WEEKLY_RECURRENCE,
+                expires: null,
+                interval: 3,
+                status: deviceapis.pim.calendar.CANCELLED_STATUS,
+                alarmTrigger: 3,
+                alarmType: deviceapis.pim.calendar.SOUND_ALARM
+            };
+        TestCalendar.updateEvent(newValues)
+    },
+
+    //Cal045
+    test_updateEvent4: function()
+    {
+        var newValues = {
+                description:'updated description 4',
+                summary:'Updated Test Event 4',
+                startTime: new Date(2014, 04, 04, 04, 04),
+                duration: 44,
+                location:'London 4',
+                categories: ["SPRC 4"],
+                recurrence: deviceapis.pim.calendar.MONTHLY_RECURRENCE,
+                expires: new Date(2015, 03, 03, 03, 03),
+                interval: 4,
+                status: deviceapis.pim.calendar.CANCELLED_STATUS,
+                alarmTrigger: 4,
+                alarmType: deviceapis.pim.calendar.SOUND_ALARM
+            };
+        TestCalendar.updateEvent(newValues)
+    },
+
+    //Cal046
+    test_updateEvent5: function()
+    {
+        var newValues = {
+                description:'updated description 5',
+                summary:'Updated Test Event 5',
+                startTime: new Date(2015, 05, 05, 05, 05),
+                duration: 55,
+                location:'London 5',
+                categories: ["SPRC 5"],
+                recurrence: deviceapis.pim.calendar.YEARLY_RECURRENCE,
+                expires: new Date(2016, 03, 03, 03, 03),
+                interval: 5,
+                status: deviceapis.pim.calendar.CANCELLED_STATUS,
+                alarmTrigger: -5,
+                alarmType: deviceapis.pim.calendar.SOUND_ALARM
+            };
+        TestCalendar.updateEvent(newValues)
+    },
+
+    //Cal047
+    test_updateEventNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent");
+    },
+
+    //Cal048
+    test_updateEventNullCallbacksParams: function()
+    {
+        var event = TestCalendar.createTestEvent();
+        testNoExceptionWithMessage("updateEvent() null callbacks",
+            function()
+            {
+                TestCalendar.calendar.updateEvent(null, null, event);
+            }
+        );
+        testNoExceptionWithMessage("updateEvent() undefined callbacks",
+            function()
+            {
+                TestCalendar.calendar.updateEvent(undefined, undefined, event);
+            }
+        );
+        testNoExceptionWithMessage("updateEvent() undefined success callback, null error callback",
+            function()
+            {
+                TestCalendar.calendar.updateEvent(undefined, null, event);
+            }
+        );
+        testNoExceptionWithMessage("updateEvent() null success callback, undefined error callback",
+            function()
+            {
+                TestCalendar.calendar.updateEvent(null, undefined, event);
+            }
+        );
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent", 1, undefined, event);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent", "test", undefined, event);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent", undefined, 1, event);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent", undefined, "test", event);
+    },
+
+    //Cal049
+    test_updateEventWrongEventParam: function()
+    {
+        function onUnexpectedCallback()
+        {
+            TestEngine.test("updateEvent() unexpected callback", false);
+        }
+        function onSuccess()
+        {
+            TestEngine.test("updateEvent() unexpected success callback invoked", false);
+        }
+
+        function onError(response)
+        {
+            TestEngine.test("updateEvent() error callback invoked", response.code == INVALID_VALUES_ERR);
+        }
+
+        var objCb = TestEngine.registerCallback("Update event with undefined filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.updateEvent(objCb.successCallback,
+            objCb.errorCallback, null);
+
+        objCb = TestEngine.registerCallback("Update event with undefined filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.updateEvent(objCb.successCallback,
+            objCb.errorCallback, undefined);
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent",
+            onUnexpectedCallback, onUnexpectedCallback, 22);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent",
+            onUnexpectedCallback, onUnexpectedCallback, "test");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent",
+            onUnexpectedCallback, onUnexpectedCallback);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "updateEvent",
+            onUnexpectedCallback, onUnexpectedCallback, new Date());
+    },
+
+    //Cal050
+    test_deleteEvent: function()
+    {
+        var foundEventsFlag = 0;
+
+        function onError()
+        {
+            TestEngine.test("deleteEvent() error callback invoked", false);
+        }
+
+        function onSuccessDeleteEvent()
+        {
+            TestEngine.test("deleteEvent() success callback invoked", true);
+            findEvents();
+        }
+
+        function onSuccessFindEvents(response)
+        {
+            TestEngine.log("deleteEvent() callback entered");
+            if (foundEventsFlag == 0) {
+                //this validation is only for the first call
+                TestEngine.test("Events for delete found", response.length > 0);
+            }
+            foundEventsFlag = 1;
+            if (response.length > 0) {
+                var objCb = TestEngine.registerCallback("deleteEvents",
+                    onSuccessDeleteEvent,
+                    onError);
+                TestCalendar.calendar.deleteEvent(objCb.successCallback,
+                    objCb.errorCallback, response[0].id);
+            }
+            else {
+                TestEngine.test("All events deleted", true);
+            }
+        }
+
+        function findEvents()
+        {
+            //find all events
+            var objCb = TestEngine.registerCallback("deleteEvent",
+                onSuccessFindEvents,
+                onError);
+            TestCalendar.calendar.findEvents(objCb.successCallback,
+                objCb.errorCallback);
+        }
+        //recursively delete all events
+        findEvents();
+    },
+
+    //Cal051
+    test_deleteEventNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent");
+    },
+
+    //Cal052
+    test_deleteEventNullCallbacksParams: function()
+    {
+        testNoExceptionWithMessage("deleteEvent() null callbacks",
+            function()
+            {
+                TestCalendar.calendar.deleteEvent(null, null, "1");
+            }
+        );
+        testNoExceptionWithMessage("deleteEvent() undefined callbacks",
+            function()
+            {
+                TestCalendar.calendar.deleteEvent(undefined, undefined, event);
+            }
+        );
+        testNoExceptionWithMessage("deleteEvent() undefined success callback, null error callback",
+            function()
+            {
+                TestCalendar.calendar.deleteEvent(undefined, null, event);
+            }
+        );
+        testNoExceptionWithMessage("deleteEvent() null success callback, undefined error callback",
+            function()
+            {
+                TestCalendar.calendar.deleteEvent(null, undefined, event);
+            }
+        );
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent", 1, undefined, "1");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent", "test", undefined, "1");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent", undefined, 1, "1");
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent", undefined, "test", "1");
+    },
+
+    //Cal053
+    test_deleteEventWrongEventParam: function()
+    {
+        function onUnexpectedCallback()
+        {
+            TestEngine.test("deleteEvent() unexpected callback", false);
+        }
+        function onSuccess()
+        {
+            TestEngine.test("deleteEvent() unexpected success callback invoked", false);
+        }
+
+        function onError(response)
+        {
+            TestEngine.test("deleteEvent() error callback invoked", response.code == NOT_FOUND_ERR);
+        }
+
+        var objCb = TestEngine.registerCallback("Delete event with null filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.deleteEvent(objCb.successCallback,
+            objCb.errorCallback, null);
+
+        objCb = TestEngine.registerCallback("Delete event with undefined filter param",
+            onSuccess,
+            onError);
+        TestCalendar.calendar.deleteEvent(objCb.successCallback,
+            objCb.errorCallback, undefined);
+
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent",
+                onUnexpectedCallback, onUnexpectedCallback, 22);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent",
+                onUnexpectedCallback, onUnexpectedCallback);
+        TestEngine.catchErrorType("code", TYPE_MISMATCH_ERR, TestCalendar.calendar, "deleteEvent",
+                onUnexpectedCallback, onUnexpectedCallback, new Date());
+    },
+
+    test_concatCategoryArray: function()
+    {
+        var category1 = "SPRC category";
+        var category2 = "test";
+        var category3 = "test2";
+        var category4 = "test aaa";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        TestEngine.test("category array has one element", event.categories.length === 1);
+        TestEngine.test("category array has proper value", event.categories[0] === category1);
+        var concatArray = event.categories.concat([category2, category3]);
+        TestEngine.test("concatenated category array has three elements", concatArray.length === 3);
+        TestEngine.test("concatenated category array has proper value [0]", concatArray[0] === category1);
+        TestEngine.test("concatenated category array has proper value [1]", concatArray[1] === category2);
+        TestEngine.test("concatenated category array has proper value [2]", concatArray[2] === category3);
+        concatArray = event.categories.concat([category2, category3], [category4]);
+        TestEngine.test("concatenated category array has four elements", concatArray.length === 4);
+        TestEngine.test("concatenated category array has proper value [0]", concatArray[0] === category1);
+        TestEngine.test("concatenated category array has proper value [1]", concatArray[1] === category2);
+        TestEngine.test("concatenated category array has proper value [2]", concatArray[2] === category3);
+        TestEngine.test("concatenated category array has proper value [3]", concatArray[3] === category4);
+        TestEngine.test("category array still has one element", event.categories.length === 1);
+    },
+
+    test_joinCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        event.categories[1] = category2;
+        event.categories[2] = category3;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("joining with default separator", event.categories.join()  === category1 + "," + category2 + "," + category3);
+        TestEngine.test("joining with space separator", event.categories.join(" ") === category1 + " " + category2 + " " + category3);
+        TestEngine.test("joining with longer string separator", event.categories.join(" how about ") === category1 + " how about " + category2 + " how about " + category3);
+        TestEngine.test("category array still has three elements", event.categories.length === 3);
+    },
+
+    test_popCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        event.categories[1] = category2;
+        event.categories[2] = category3;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("poped element has correct value", event.categories.pop() === category3);
+        TestEngine.test("category array has three elements", event.categories.length === 2);
+        TestEngine.test("poped element has correct value", event.categories.pop() === category2);
+        TestEngine.test("category array has three elements", event.categories.length === 1);
+        TestEngine.test("poped element has correct value", event.categories.pop() === category1);
+        TestEngine.test("category array has three elements", event.categories.length === 0);
+        TestEngine.test("poped element has correct value", event.categories.pop() === undefined);
+        TestEngine.test("poped element has correct value", event.categories.pop() === undefined);
+    },
+
+    test_pushCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories.push(category1);
+        event.categories.push(category2);
+        event.categories.push(category3);
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("array element [0] has correct value", event.categories[0] === category1);
+        TestEngine.test("array element [1] has correct value", event.categories[1] === category2);
+        TestEngine.test("array element [2] has correct value", event.categories[2] === category3);
+    },
+
+    test_reverseCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var category4 = "category3";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories.push(category1);
+        event.categories.push(category2);
+        event.categories.push(category3);
+        event.categories.push(category4);
+        event.categories.reverse();
+        TestEngine.test("category array has four elements", event.categories.length === 4);
+        TestEngine.test("array element [0] has correct value", event.categories[0] === category4);
+        TestEngine.test("array element [1] has correct value", event.categories[1] === category3);
+        TestEngine.test("array element [2] has correct value", event.categories[2] === category2);
+        TestEngine.test("array element [3] has correct value", event.categories[3] === category1);
+    },
+
+    test_shiftCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        event.categories[1] = category2;
+        event.categories[2] = category3;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("shifted element has correct value", event.categories.shift() === category1);
+        TestEngine.test("category array has three elements", event.categories.length === 2);
+        TestEngine.test("shifted element has correct value", event.categories.shift() === category2);
+        TestEngine.test("category array has three elements", event.categories.length === 1);
+        TestEngine.test("shifted element has correct value", event.categories.shift() === category3);
+        TestEngine.test("category array has three elements", event.categories.length === 0);
+        TestEngine.test("shifted element has correct value", event.categories.shift() === undefined);
+        TestEngine.test("shifted element has correct value", event.categories.shift() === undefined);
+    },
+
+    test_sliceCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        event.categories[1] = category2;
+        event.categories[2] = category3;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        var slice = event.categories.slice(0, 2);
+        TestEngine.test("slice array has correct number of elements", slice.length === 3);
+        slice = event.categories.slice(0, 1);
+        TestEngine.test("slice array has correct number of elements", slice.length === 2);
+        slice = event.categories.slice(0, 0);
+        TestEngine.test("slice array has correct number of elements", slice.length === 1);
+        slice = event.categories.slice(0);
+        TestEngine.test("slice array has correct number of elements", slice.length === 3);
+        slice = event.categories.slice(1);
+        TestEngine.test("slice array has correct number of elements", slice.length === 2);
+        slice = event.categories.slice(2);
+        TestEngine.test("slice array has correct number of elements", slice.length === 1);
+        slice = event.categories.slice(3);
+        TestEngine.test("slice array has correct number of elements", slice.length === 0);
+    },
+
+    test_sortCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category3;
+        event.categories[1] = category2;
+        event.categories[2] = category1;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        event.categories.sort();
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("array element [0] has correct value", event.categories[0] === category1);
+        TestEngine.test("array element [1] has correct value", event.categories[1] === category2);
+        TestEngine.test("array element [2] has correct value", event.categories[2] === category3);
+    },
+
+    test_toStringCategoryArray: function()
+    {
+        var category1 = "category0";
+        var category2 = "category1";
+        var category3 = "category2";
+        var event = TestCalendar.createTestEvent();
+        TestEngine.test("category array is empty", event.categories.length === 0);
+        event.categories[0] = category1;
+        event.categories[1] = category2;
+        event.categories[2] = category3;
+        TestEngine.test("category array has three elements", event.categories.length === 3);
+        TestEngine.test("toString return correct value", event.categories.join() === category1 + "," + category2 + "," + category3);
+    }
+};
+//=============================================================================
+TestEngine.setTestSuiteName("[WAC2.0][Calendar]");
+////Cal001
+//TestEngine.addTest(true,TestCalendar.test_modulePresence, "[WAC2.0][Calendar] Test calendar module presence");
+////Cal002
+//TestEngine.addTest(true,TestCalendar.test_calendarManagerConstants, "[WAC2.0][Calendar] Calendar manager constants");
+////Cal003
+TestEngine.addTest(true,TestCalendar.test_getCalendar, "[WAC2.0][Calendar] Get calendar");
+////Cal004
+//TestEngine.addTest(true,TestCalendar.test_getCalendarNoCallbacks, "[WAC2.0][Calendar] Get calendar with no callbacks");
+////Cal005
+//TestEngine.addTest(true,TestCalendar.test_getCalendarInvalidCallbacks, "[WAC2.0][Calendar] Get calendar with invalid callbacks");
+////Cal006
+//TestEngine.addTest(true,TestCalendar.test_calendarMethodsPresence, "[WAC2.0][Calendar] Calendar methods presence");
+////Cal007
+//TestEngine.addTest(true,TestCalendar.test_getCalendarName, "[WAC2.0][Calendar] Get calendar name");
+////Cal008
+//TestEngine.addTest(true,TestCalendar.test_getCalendarType, "[WAC2.0][Calendar] Get calendar type");
+////Cal009
+//TestEngine.addTest(true,TestCalendar.test_createEmptyEvent, "[WAC2.0][Calendar] Create empty event");
+////Cal010
+//TestEngine.addTest(true,TestCalendar.test_eventAttributes, "[WAC2.0][Calendar] event attributes");
+////Cal011
+//TestEngine.addTest(true,TestCalendar.test_createEvent, "[WAC2.0][Calendar] Create event");
+//
+////Cal012
+//TestEngine.addTest(true,TestCalendar.test_addEvent1, "[WAC2.0][Calendar] Add event 1");
+////Cal013
+//TestEngine.addTest(true,TestCalendar.test_addEvent2, "[WAC2.0][Calendar] Add event 2");
+////Cal014
+//TestEngine.addTest(true,TestCalendar.test_addEvent3, "[WAC2.0][Calendar] Add event 3");
+////Cal015
+//TestEngine.addTest(true,TestCalendar.test_addEvent4, "[WAC2.0][Calendar] Add event 4");
+////Cal016
+//TestEngine.addTest(true,TestCalendar.test_addEvent5, "[WAC2.0][Calendar] Add event 5");
+////Cal017
+//TestEngine.addTest(true,TestCalendar.test_addEvent6, "[WAC2.0][Calendar] Add event 6");
+////Cal019
+//TestEngine.addTest(true,TestCalendar.test_addEventNoParams, "[WAC2.0][Calendar] Add event with no params");
+////Cal020
+//TestEngine.addTest(true,TestCalendar.test_addEventInvalidCallbacksParams, "[WAC2.0][Calendar] Add event with wrong callbacks");
+////Cal021
+//TestEngine.addTest(true,TestCalendar.test_addEventWrongEventParam, "[WAC2.0][Calendar] Add event with wrong event param");
+//
+////Cal022
+//TestEngine.addTest(true,TestCalendar.test_findAllEvents, "[WAC2.0][Calendar] Find all events");
+////Cal023
+//TestEngine.addTest(true,TestCalendar.test_findEventsId, "[WAC2.0][Calendar] Find events, filter: id");
+////Cal024
+//TestEngine.addTest(true,TestCalendar.test_findEventsSummary, "[WAC2.0][Calendar] Find events, filter: summary");
+////Cal025
+//TestEngine.addTest(true,TestCalendar.test_findEventsDescription, "[WAC2.0][Calendar] Find events, filter: description");
+////Cal026
+//TestEngine.addTest(true,TestCalendar.test_findEventsLocation, "[WAC2.0][Calendar] Find events, filter: location");
+////Cal027
+//TestEngine.addTest(true,TestCalendar.test_findEventsCategory, "[WAC2.0][Calendar] Find events, filter: category");
+////Cal028
+//TestEngine.addTest(true,TestCalendar.test_findEventsStatus, "[WAC2.0][Calendar] Find events, filter: status");
+////Cal029
+//TestEngine.addTest(true,TestCalendar.test_findEventsFullStartTime, "[WAC2.0][Calendar] Find events, filter: initialStartDate and endStartDate");
+////Cal030
+//TestEngine.addTest(true,TestCalendar.test_findEventsInitialStartDate, "[WAC2.0][Calendar] Find events, filter: initialStartDate");
+////Cal031
+//TestEngine.addTest(true,TestCalendar.test_findEventsEndStartDate, "[WAC2.0][Calendar] Find events, filter: endStartDate");
+////Cal032
+//TestEngine.addTest(true,TestCalendar.test_findEventsEmptyFilter, "[WAC2.0][Calendar] Find events, filter: empty filter");
+////Cal033
+//TestEngine.addTest(true,TestCalendar.test_findEventsFullStartTimeNoResults, "[WAC2.0][Calendar] Find events, no results, filter: initialStartDate and endStartDate");
+////Cal034
+//TestEngine.addTest(true,TestCalendar.test_findEventsLocationNoResults, "[WAC2.0][Calendar] Find events, no results, filter: location");
+////Cal035
+//TestEngine.addTest(true,TestCalendar.test_findEventsSummaryNoResults, "[WAC2.0][Calendar] Find events, no results, filter: summary");
+////Cal036
+//TestEngine.addTest(true,TestCalendar.test_findEventsDescriptionNoResults, "[WAC2.0][Calendar] Find events, no results, filter: description");
+////Cal037
+//TestEngine.addTest(true,TestCalendar.test_findEventsIdNoResults, "[WAC2.0][Calendar] Find events, no results, filter: id");
+////Cal038
+//TestEngine.addTest(true,TestCalendar.test_findEventsCategoryNoResults, "[WAC2.0][Calendar] Find events, no results, filter: category");
+////Cal039
+//TestEngine.addTest(true,TestCalendar.test_findEventsNoParams, "[WAC2.0][Calendar] Find events with no params");
+////Cal040
+//TestEngine.addTest(true,TestCalendar.test_findEventsNoCallbacksParams, "[WAC2.0][Calendar] Find events with no callbacks");
+////Cal041
+//TestEngine.addTest(true,TestCalendar.test_findEventsWrongFilterParam, "[WAC2.0][Calendar] Find events with wrong filter param");
+//
+////Cal042
+//TestEngine.addTest(true,TestCalendar.test_updateEvent1, "[WAC2.0][Calendar] Update event 1");
+////Cal043
+//TestEngine.addTest(true,TestCalendar.test_updateEvent2, "[WAC2.0][Calendar] Update event 2");
+////Cal044
+//TestEngine.addTest(true,TestCalendar.test_updateEvent3, "[WAC2.0][Calendar] Update event 3");
+////Cal045
+//TestEngine.addTest(true,TestCalendar.test_updateEvent4, "[WAC2.0][Calendar] Update event 4");
+////Cal046
+//TestEngine.addTest(true,TestCalendar.test_updateEvent5, "[WAC2.0][Calendar] Update event 5");
+////Cal047
+//TestEngine.addTest(true,TestCalendar.test_updateEventNoParams, "[WAC2.0][Calendar] Update event with no params");
+////Cal048
+//TestEngine.addTest(true,TestCalendar.test_updateEventNullCallbacksParams, "[WAC2.0][Calendar] Update event with wrong callbacks");
+////Cal049
+//TestEngine.addTest(true,TestCalendar.test_updateEventWrongEventParam, "[WAC2.0][Calendar] Update event with wrong event param");
+//
+////Cal050
+//TestEngine.addTest(true,TestCalendar.test_deleteEvent, "[WAC2.0][Calendar] Delete event");
+////Cal051
+//TestEngine.addTest(true,TestCalendar.test_deleteEventNoParams, "[WAC2.0][Calendar] Delete event with no params");
+////Cal052
+//TestEngine.addTest(true,TestCalendar.test_deleteEventNullCallbacksParams, "[WAC2.0][Calendar] Delete event with wrong callbacks");
+////Cal053
+//TestEngine.addTest(true,TestCalendar.test_deleteEventWrongEventParam, "[WAC2.0][Calendar] Delete event with wrong event param");
+//
+////Cal050
+//TestEngine.addTest(true,TestCalendar.test_concatCategoryArray, "[WAC2.0][Calendar] Concat category array");
+////Cal051
+//TestEngine.addTest(true,TestCalendar.test_joinCategoryArray, "[WAC2.0][Calendar] Join category array");
+////Cal052
+//TestEngine.addTest(true,TestCalendar.test_popCategoryArray, "[WAC2.0][Calendar] Pop category array");
+////Cal053
+//TestEngine.addTest(true,TestCalendar.test_pushCategoryArray, "[WAC2.0][Calendar] Push category array");
+////Cal054
+//TestEngine.addTest(true,TestCalendar.test_reverseCategoryArray, "[WAC2.0][Calendar] Reverse category array");
+////Cal055
+//TestEngine.addTest(true,TestCalendar.test_shiftCategoryArray, "[WAC2.0][Calendar] Shift category array");
+////Cal056
+//TestEngine.addTest(true,TestCalendar.test_sliceCategoryArray, "[WAC2.0][Calendar] Slice category array");
+////Cal057
+//TestEngine.addTest(true,TestCalendar.test_sortCategoryArray, "[WAC2.0][Calendar] Sort category array");
+////Cal058
+//TestEngine.addTest(true,TestCalendar.test_toStringCategoryArray, "[WAC2.0][Calendar] toString category array");
+
+//=============================================================================
+
+function testNoExceptionWithMessage(message, fun) {
+    var testResult = true;
+    try
+    {
+        fun();
+    }
+    catch (e)
+    {
+        testResult = false;
+    }
+    TestEngine.test(message, testResult);
+}
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestCamera.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestCamera.js
new file mode 100644 (file)
index 0000000..d2e8bbf
--- /dev/null
@@ -0,0 +1,1205 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test for camera module classes.
+ *
+ * @author      Wojciech Bielawski (w.bielawski@samsung.com)
+ * @version     0.1
+ */
+
+var gcameras;
+var mainCamera;
+var callbackExecuted = false;
+var previewId = "cameraPreview";
+
+var VideoTime = 5000;
+
+TestEngine.setErrorType(Object);
+TestEngine.setErrorField('code');
+var TYPE_MISMATCH_ERR = 17;
+var INVALID_VALUES_ERR = 22;
+var SECURITY_ERR = 18;
+var NOT_FOUND_ERR = 8;
+
+
+/*
+ * Function to generate unique filename
+ */
+function GetFileName(prefix, suffix)
+{
+    var date = new Date();
+    var name = prefix + date.getTime() + suffix;
+    TestEngine.log(name);
+    return name;
+}
+
+function waitMs(ms)
+{
+    ms += new Date().getTime();
+    while (new Date() < ms){}
+}
+
+
+function acceptError()
+{
+    TestEngine.test("Error occure", true);
+}
+
+function rejectSuccess()
+{
+    TestEngine.test("Success - error expected", false);
+}
+
+/* Cam001 */
+function TestGetCameras()
+{
+    var obj = TestEngine.registerCallback(
+        "getCameras",
+        rejectSuccess,
+        acceptError);
+//    var obj = TestEngine.registerCallback(
+//        "getCameras",
+//        function(cameras){
+//            if (cameras.length > 0) {
+//                gcameras = cameras;
+//                mainCamera = cameras[0];
+//                TestEngine.log("Cameras size: " + cameras.length);
+//                TestEngine.test("Size of cameras array", cameras.length == 2);
+//            } else {
+//                TestEngine.logErr("No camera found");
+//            }
+//        },
+//        function(err){
+//            TestEngine.logErr("Get cameras failed. Exception code: " + err.code);
+//        });
+    try {
+        deviceapis.camera.getCameras(obj.successCallback, obj.errorCallback);
+    } catch(e) {
+        TestEngine.logErr("Exception while getting cameras");
+    }
+}
+
+/* Cam002 */
+function TestCaseCameraArrayProperties()
+{
+    TestEngine.test("Camera array", isArray(gcameras));
+    TestEngine.test("Camera array length", gcameras.length == 2);
+}
+
+function TestJavaScript()
+{
+    try
+    {
+        var divElement = document.getElementById("video");
+        var para = document.createElement("p");
+        para.setAttribute("style","color:blue;");
+        var text = document.createTextNode("this is my text");
+        para.appendChild(text);
+        divElement.appendChild(para);
+    }
+    catch(e)
+    {
+        TestEngine.log("Exception: " + e);
+    }
+    TestEngine.log("Test finish");
+}
+
+/* Cam003 */
+function TestCameraFunctionality_PreviewStart()
+{
+    TestEngine.log("Create Preview");
+
+    function successCallback(obj)
+    {
+        try
+        {
+            TestEngine.test("Type of preview node", "object" === typeof(obj));
+            var divElement = document.getElementById("video");
+            TestEngine.test("Type of preview node parent", "object" === typeof(divElement));
+            divElement.appendChild(obj);
+            obj.id = previewId;
+            TestEngine.test("preview node id", previewId === obj.id);
+            obj.style.visibility = "visible";
+            TestEngine.test("Preview created", true);
+        }
+        catch(e)
+        {
+            TestEngine.test("Preview created", false);
+            TestEngine.logErr("exception: " + e);
+        }
+    }
+
+    function errorCallback()
+    {
+        TestEngine.test("Preview created", false);
+    }
+
+    try
+    {
+        var obj = TestEngine.registerCallback(
+                "createPreviewNode",
+                successCallback,
+                errorCallback);
+                gcameras[0].createPreviewNode(obj.successCallback, obj.errorCallback);
+    }
+    catch(e)
+    {
+        TestEngine.test("Preview created", false);
+        TestEngine.logErr("exception: " + e);
+    }
+}
+
+function TestCameraFunctionality_PreviewStop()
+{
+    function stopFunction()
+    {
+        TestEngine.log("stopping");
+        var divElement = document.getElementById("video");
+        var previewNode = document.getElementById(previewId);
+
+        TestEngine.test("Type of preview node parent", "object" === typeof(divElement));
+        TestEngine.test("Type of preview node parent", "object" === typeof(previewNode));
+
+        previewNode.style.visibility = "hidden";
+        divElement.removeChild(previewNode);
+
+        TestEngine.test("Preview removed", true);
+    }
+
+    var timeout = 5000;
+    TestEngine.log("preview will end in " + timeout + " miliseconds");
+    var obj = TestEngine.registerCallback(
+            "createPreviewNode",
+            stopFunction,
+            undefined);
+    setTimeout(obj.successCallback, timeout);
+}
+
+function TestCameraFunctionality_TakePicture()
+{
+    function success(filename)
+    {
+        TestEngine.log("filename = " + filename);
+        TestEngine.test("image captured", true)
+    }
+
+    function error(e)
+    {
+        TestEngine.test("image captured", false)
+    }
+
+    TestEngine.log("Take picutre");
+    var requestedFileName = GetFileName("images/test_photo_",".jpg");
+    var obj = TestEngine.registerCallback("captureImage", success, error);
+    gcameras[0].captureImage(obj.successCallback,
+                             obj.errorCallback,
+                             {destinationFilename:requestedFileName, highRes:false});
+}
+
+var callbackExecuted = false;
+function TestCameraFunctionality_Video()
+{
+    //wait for stabilization
+    waitMs(3000);
+
+    function success(filename)
+    {
+        TestEngine.test("video capture", true);
+        callbackExecuted = true;
+    }
+
+    function error(e)
+    {
+        TestEngine.test("video captured", false);
+        callbackExecuted = true;
+    }
+
+    function checkCompletness()
+    {
+        if(!callbackExecuted)
+        {
+            TestEngine.test("Video capture time out", false);
+        }
+    }
+
+    TestEngine.log("Video Recording");
+    var requestedFileName = GetFileName("videos/test_video_",".mp4");
+    var obj = TestEngine.registerCallback("captureVideo", success, error);
+    gcameras[0].startVideoCapture(obj.successCallback,
+                                  obj.errorCallback,
+                                  {destinationFilename:requestedFileName, highRes:false});
+    TestEngine.log("Start :" + Date());
+
+    function stopVideo()
+    {
+        try{
+            TestEngine.log("Stop :" + Date());
+            gcameras[0].stopVideoCapture();
+
+            TestEngine.log("Wait :" + Date());
+            //check if allback has been executed
+            setTimeout(checkCompletness, 10000);
+        }
+        catch(e)
+        {
+            TestEngine.log("Exception: " + e);
+        }
+    }
+
+    setTimeout(stopVideo, VideoTime);
+}
+
+function TestCameraCancel()
+{
+    var number =5;
+
+    var expectedPhotos = 4;
+
+    var done = 0;
+
+
+
+    function success(filename)
+    {
+        done = done +1;
+        TestEngine.log("filename = " + filename);
+        TestEngine.test("image captured", true)
+        checkStatus();
+    }
+
+    function error(e)
+    {
+        done = done +1;
+        checkStatus();
+    }
+
+    var obj = TestEngine.registerCallback("cancel test ", testPassed, testFail);
+
+    function checkStatus()
+    {
+        if(done > expectedPhotos)
+        {
+            obj.errorCallback();
+        }
+
+        if(done == expectedPhotos)
+        {
+            obj.successCallback();
+        }
+    }
+
+    function testFail()
+    {
+            TestEngine.test("Cancel take picture", false)
+    }
+
+    function testPassed()
+    {
+            TestEngine.test("Cancel take picture", true)
+    }
+
+
+    TestEngine.log("Take picutre");
+    for (i=1;i<number+1;i++)
+    {
+        var requestedFileName = GetFileName("images/test_photo_"+i+"_",".jpg");
+
+        var pending=gcameras[0].captureImage(success,
+                                 error,
+                                 {destinationFilename:requestedFileName, highRes:false});
+
+        if(i==4){
+            TestEngine.log("Operation will be canceled");
+            pending.cancel();
+            TestEngine.log("Operation should be canceled");
+        }
+  }
+
+
+}
+
+//******************************* new to review below *******************************
+
+function parameterCorrectnessSuccessCallback(){
+    TestEngine.logErr("SuccessCallback on invalid parameter");
+}
+
+function parameterCorrectnessErrorCallback(err){
+    TestEngine.logErr("ErrorCallback invoked on invalid parameter (error should be thrown)");
+}
+
+// Cam0014
+// Input: errorCallback = null, others = valid
+// Result: Test passes.
+function TestGetCamerasNullErrorCallback()
+{
+    function GetCamerasOnSuccess(cameras)
+    {
+        TestEngine.test("getCameras()", isArray(cameras));
+    }
+
+    var cb = TestEngine.registerCallback("getCameras", GetCamerasOnSuccess, null);
+    deviceapis.camera.getCameras(cb.successCallback, null);
+}
+
+// Cam0015
+// Input: successCallback = null, others = valid
+// Result: Test fails with error callback called with INVALID_VALUES_ERR.
+function TestGetCamerasNullSuccessCallback()
+{
+    function GetCamerasOnError(error)
+    {
+        TestEngine.test("getCameras()", (error.code == INVALID_VALUES_ERR));
+    }
+
+    var cb = TestEngine.registerCallback("getCameras", null, GetCamerasOnError);
+    deviceapis.camera.getCameras(null, cb.errorCallback);
+}
+
+// Cam0016
+// Input: successCallback = undefined, others = valid
+// Result: Test fails with TYPE_MISMATCH_ERR thrown in place.
+function TestGetCamerasUndefinedSuccessCallback()
+{
+    function GetCamerasOnError(error)
+    {
+        TestEngine.test("getCameras()", false);
+    }
+
+    TestEngine.testPresetError(
+        "getCameras()",
+        function() {
+            deviceapis.camera.getCameras(undefined, GetCamerasOnError);
+        },
+        TYPE_MISMATCH_ERR
+    );
+}
+
+// Cam0017
+// Input: successCallback = null, errorCallback = null
+// Result: Test fails silently.
+function TestGetCamerasNullCallbacks()
+{
+    testNoExceptionWithMessage("getCameras()", function() {
+        deviceapis.camera.getCameras(null, null);
+    });
+}
+
+// Cam0018
+// Input: errorCallback = not passed, others = valid
+// Result: Test passes.
+function TestGetCamerasNoErrorCallback()
+{
+    function GetCamerasOnSuccess(cameras)
+    {
+        TestEngine.test("getCameras()", isArray(cameras));
+    }
+
+    var cb = TestEngine.registerCallback("getCameras", GetCamerasOnSuccess, null);
+    deviceapis.camera.getCameras(cb.successCallback);
+}
+
+// Cam0019
+// Result: Test passes.
+function TestCameraId()
+{
+    TestEngine.test("camaras available", isArray(gcameras) && gcameras.length > 0);
+    for (var i = 0; i < gcameras.length; ++i) {
+        TestEngine.test("id", gcameras[i].id === "front" || gcameras[i].id === "rear");
+    }
+}
+
+// Cam0020
+// Input: options = null, others = valid
+// Result: Test passes.
+function TestCaptureImageNullOptions()
+{
+    function CaptureImageOnSuccess(filename)
+    {
+        TestEngine.test("captureImage()", true);
+    }
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", false)
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, CaptureImageOnError);
+    gcameras[0].captureImage(cb.successCallback, cb.errorCallback, null);
+}
+
+// Cam0021
+// Input: options = undefined, others = valid
+// Result: Test passes.
+function TestCaptureImageUndefinedOptions()
+{
+    function CaptureImageOnSuccess(filename)
+    {
+        TestEngine.test("captureImage()", true);
+    }
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", false)
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, CaptureImageOnError);
+    gcameras[0].captureImage(cb.successCallback, cb.errorCallback, undefined);
+}
+
+// Cam0022
+// Input: errorCallback = null, others = valid
+// Result: Test passes.
+function TestCaptureImageNullErrorCallback()
+{
+    var options = {
+        destinationFilename: 'images/TestCaptureImageNullErrorCallback.jpg'
+    };
+    function CaptureImageOnSuccess(filename)
+    {
+        // Don't compare paths if 'images' is passed as virtual root since Tizen
+        // points 'images' to the same location as 'videos' and returns filename
+        // with 'videos' virtual root instead of 'images'.
+        // TestEngine.test("captureImage()", (options.destinationFilename == filename));
+        TestEngine.test("captureImage()", true);
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, null);
+    gcameras[0].captureImage(cb.successCallback, null, options);
+}
+
+// Cam0023
+// Input: successCallback = null, options = omitted, others = valid
+// Result: Test fails with error callback called with INVALID_VALUES_ERR.
+function TestCaptureImageNullSuccessCallback()
+{
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", (error.code == INVALID_VALUES_ERR));
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", null, CaptureImageOnError);
+    gcameras[0].captureImage(null, cb.errorCallback);
+}
+
+// Cam0024
+// Input: successCallback = undefined, options = omitted, others = valid
+// Result: Test fails with TYPE_MISMATCH_ERR thrown in place.
+function TestCaptureImageUndefinedSuccessCallback()
+{
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", false);
+    }
+
+    TestEngine.testPresetError(
+        "captureImage()",
+        function() {
+            gcameras[0].captureImage(undefined, CaptureImageOnError);
+        },
+        TYPE_MISMATCH_ERR
+    );
+}
+
+// Cam0025
+// Input: successCallback = null, errorCallback = null, options = omitted
+// Result: Test fails silently.
+function TestCaptureImageNullCallbacks()
+{
+    testNoExceptionWithMessage("captureImage()", function() {
+        gcameras[0].captureImage(null, null);
+    });
+}
+
+// Cam0026
+// Input: errorCallback = omitted, options = omitted, others = valid
+// Result: Test passes.
+function TestCaptureImageNoErrorCallback()
+{
+    function CaptureImageOnSuccess(filename)
+    {
+        TestEngine.test("captureImage()", true);
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, null);
+    gcameras[0].captureImage(cb.successCallback);
+}
+
+// Cam0027
+// Input: options = invalid filename, others = valid
+// Result: Test passes.
+function TestCaptureImageInvalidFilename()
+{
+    var options = {
+        destinationFilename: {}
+    };
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", false);
+    }
+    function CaptureImageOnSuccess(filename)
+    {
+        TestEngine.test("captureImage()", true);
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, CaptureImageOnError);
+    gcameras[0].captureImage(cb.successCallback, cb.errorCallback, options);
+}
+
+// Cam0028
+// Input: options = invalid highRes, others = valid
+// Result: Test passes.
+function TestCaptureImageInvalidHighRes()
+{
+    var options = {
+        highRes: {}
+    };
+    function CaptureImageOnError(error)
+    {
+        TestEngine.test("captureImage()", false);
+    }
+    function CaptureImageOnSuccess(filename)
+    {
+        TestEngine.test("captureImage()", true);
+    }
+
+    var cb = TestEngine.registerCallback("captureImage", CaptureImageOnSuccess, CaptureImageOnError);
+    gcameras[0].captureImage(cb.successCallback, cb.errorCallback, options);
+}
+
+// Cam0029
+// Input: options = null, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureNullOptions()
+{
+    function Step1()
+    {
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            TestEngine.test("startVideoCapture()", true);
+        }
+        function StartVideoCaptureOnError(error)
+        {
+            TestEngine.test("startVideoCapture()", false)
+        }
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, StartVideoCaptureOnError);
+        gcameras[0].startVideoCapture(cb.successCallback, cb.errorCallback, null);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0030
+// Input: options = undefined, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureUndefinedOptions()
+{
+    function Step1()
+    {
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            TestEngine.test("startVideoCapture()", true);
+        }
+        function StartVideoCaptureOnError(error)
+        {
+            TestEngine.test("startVideoCapture()", false)
+        }
+
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, StartVideoCaptureOnError);
+        gcameras[0].startVideoCapture(cb.successCallback, cb.errorCallback, undefined);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0031
+// Input: errorCallback = null, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureNullErrorCallback()
+{
+    function Step1()
+    {
+        var options = {
+            destinationFilename: 'images/TestStartVideoCaptureNullErrorCallback.3gp'
+        };
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            // Don't compare paths if 'images' is passed as virtual root since Tizen
+            // points 'images' to the same location as 'videos' and returns filename
+            // with 'videos' virtual root instead of 'images'.
+            // TestEngine.test("StartVideoCapture()", (options.destinationFilename == filename));
+            TestEngine.test("startVideoCapture()", true);
+        }
+
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, null);
+        gcameras[0].startVideoCapture(cb.successCallback, null, options);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0032
+// Input: successCallback = null, options = omitted, others = valid
+// Result: Test fails with error callback called with INVALID_VALUES_ERR.
+function TestStartVideoCaptureNullSuccessCallback()
+{
+    function StartVideoCaptureOnError(error)
+    {
+        TestEngine.test("startVideoCapture()", (error.code == INVALID_VALUES_ERR));
+    }
+
+    var cb = TestEngine.registerCallback("startVideoCapture", null, StartVideoCaptureOnError);
+    gcameras[0].startVideoCapture(null, cb.errorCallback);
+}
+
+// Cam0033
+// Input: successCallback = undefined, options = omitted, others = valid
+// Result: Test fails with TYPE_MISMATCH_ERR thrown in place.
+function TestStartVideoCaptureUndefinedSuccessCallback()
+{
+    function StartVideoCaptureOnError(error)
+    {
+        TestEngine.test("startVideoCapture()", false);
+    }
+
+    TestEngine.testPresetError(
+        "startVideoCapture()",
+        function() {
+            gcameras[0].startVideoCapture(undefined, StartVideoCaptureOnError);
+        },
+        TYPE_MISMATCH_ERR
+    );
+}
+
+// Cam0034
+// Input: successCallback = null, errorCallback = null, options = omitted
+// Result: Test fails silently.
+function TestStartVideoCaptureNullCallbacks()
+{
+    testNoExceptionWithMessage("startVideoCapture()", function() {
+        gcameras[0].startVideoCapture(null, null);
+    });
+}
+
+// Cam0035
+// Input: errorCallback = omitted, options = omitted, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureNoErrorCallback()
+{
+    function Step1()
+    {
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            TestEngine.test("startVideoCapture()", true);
+        }
+
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, null);
+        gcameras[0].startVideoCapture(cb.successCallback);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0036
+// Input: options = invalid filename, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureInvalidFilename()
+{
+    function Step1()
+    {
+        var options = {
+            destinationFilename: {}
+        };
+        function StartVideoCaptureOnError(error)
+        {
+            TestEngine.test("startVideoCapture()", false);
+        }
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            TestEngine.test("startVideoCapture()", true);
+        }
+
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, StartVideoCaptureOnError);
+        gcameras[0].startVideoCapture(cb.successCallback, cb.errorCallback, options);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0037
+// Input: options = invalid highRes, others = valid
+// Result: Test passes.
+function TestStartVideoCaptureInvalidHighRes()
+{
+    function Step1()
+    {
+        var options = {
+            highRes: {}
+        };
+        function StartVideoCaptureOnError(error)
+        {
+            TestEngine.test("startVideoCapture()", false);
+        }
+        function StartVideoCaptureOnSuccess(filename)
+        {
+            TestEngine.test("startVideoCapture()", true);
+        }
+
+        var cb = TestEngine.registerCallback("startVideoCapture", StartVideoCaptureOnSuccess, StartVideoCaptureOnError);
+        gcameras[0].startVideoCapture(cb.successCallback, cb.errorCallback, options);
+    }
+
+    function Step2()
+    {
+        gcameras[0].stopVideoCapture();
+    }
+
+    var steps = new Array(Step1, Step2);
+    TestEngine.executeSteps(steps, 4000);
+}
+
+// Cam0038
+// Input: errorCallback = null, others = valid
+// Result: Test passes.
+function TestCreatePreviewNodeNullErrorCallback()
+{
+    function CreatePreviewNodeOnSuccess(domObj)
+    {
+        TestEngine.test("createPreviewNode()", true);
+    }
+
+    var cb = TestEngine.registerCallback("createPreviewNode", CreatePreviewNodeOnSuccess, null);
+    gcameras[0].createPreviewNode(cb.successCallback, null);
+}
+
+// Cam0039
+// Input: successCallback = null, others = valid
+// Result: Test fails with error callback called with INVALID_VALUES_ERR.
+function TestCreatePreviewNodeNullSuccessCallback()
+{
+    function CreatePreviewNodeOnError(error)
+    {
+        TestEngine.test("createPreviewNode()", (error.code == INVALID_VALUES_ERR));
+    }
+
+    var cb = TestEngine.registerCallback("createPreviewNode", null, CreatePreviewNodeOnError);
+    gcameras[0].createPreviewNode(null, cb.errorCallback);
+}
+
+// Cam0040
+// Input: successCallback = undefined, others = valid
+// Result: Test fails with TYPE_MISMATCH_ERR thrown in place.
+function TestCreatePreviewNodeUndefinedSuccessCallback()
+{
+    function CreatePreviewNodeOnError(error)
+    {
+        TestEngine.test("createPreviewNode()", false);
+    }
+
+    TestEngine.testPresetError(
+        "createPreviewNode()",
+        function() {
+            gcameras[0].createPreviewNode(undefined, CreatePreviewNodeOnError);
+        },
+        TYPE_MISMATCH_ERR
+    );
+}
+
+// Cam0041
+// Input: successCallback = null, errorCallback = null
+// Result: Test fails silently.
+function TestCreatePreviewNodeNullCallbacks()
+{
+    testNoExceptionWithMessage("createPreviewNode()", function() {
+        gcameras[0].createPreviewNode(null, null);
+    });
+}
+
+// Cam0042
+// Input: errorCallback = not passed, others = valid
+// Result: Test passes.
+function TestCreatePreviewNodeNoErrorCallback()
+{
+    function CreatePreviewNodeOnSuccess(domObj)
+    {
+        TestEngine.test("createPreviewNode()", true);
+    }
+
+    var cb = TestEngine.registerCallback("createPreviewNode", CreatePreviewNodeOnSuccess, null);
+    gcameras[0].createPreviewNode(cb.successCallback);
+}
+
+//=============================================================================
+//TestJavaScript();
+
+function SimpleVideoTest()
+{
+    TestEngine.log ("START")
+
+    function Succ(cameras){
+        gcameras = cameras;
+        Record();
+    }
+
+    function Errr(err){
+        TestEngine.logErr("Get cameras failed. Exception code: " + err.code);
+    }
+
+    deviceapis.camera.getCameras(Succ, Errr);
+}
+
+function Record()
+{
+
+    function success(filename)
+    {
+        TestEngine.log("video capture success");
+        callbackExecuted = true;
+    }
+
+    function errorCb(e)
+    {
+        TestEngine.log("video captured errro");
+        callbackExecuted = true;
+    }
+
+    var requestedFileName = GetFileName("videos/test_video_",".mp4");
+    TestEngine.log("Start 1:" + Date());
+    gcameras[0].startVideoCapture(success,
+                                  errorCb,
+                                  {destinationFilename:requestedFileName, highRes:false});
+    TestEngine.log("Start 2:" + Date());
+
+//    waitMs(7000);
+//    gcameras[0].stopVideoCapture();
+//    TestEngine.log("Stop :" + Date());
+
+    function stopVideo()
+    {
+        try{
+            TestEngine.log("Stop :" + Date());
+            gcameras[0].stopVideoCapture();
+
+            TestEngine.log("Wait :" + Date());
+            //time for invoke callback
+            waitMs(3000);
+            TestEngine.log("After Wait :" + Date());
+
+            if(!callbackExecuted)
+            {
+                TestEngine.test("Video capture time out", false);
+            }
+        }
+        catch(e)
+        {
+            TestEngine.log("Exception: " + e);
+        }
+    }
+    TestEngine.log("Before timeout")
+    setTimeout(stopVideo, VideoTime);
+}
+
+function onCameraError(err)
+{
+    TestEngine.test("Camera error: " + err.code, false);
+}
+
+function TestGetImageOK()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image1.jpg",
+        function(fileName) {
+            TestEngine.test("Take picture image1.jpg : " + fileName,
+                            fileName === "images/image1.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image1.jpg",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+function TestGetImageOK2()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image2.jpeg",
+        function(fileName) {
+            TestEngine.test("Take picture image2.jpeg : " + fileName,
+                            fileName === "images/image2.jpeg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image2.jpeg",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+
+function TestGetImagePnG()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image3.PnG",
+        function(fileName) {
+            TestEngine.test("Take picture image3.PnG : " + fileName,
+                            fileName === "images/image3.PnG" || fileName === "images/image3.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image3.PnG",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+
+function TestGetImageNoExt()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image4",
+        function(fileName) {
+            TestEngine.test("Take picture image4 : " + fileName,
+                            fileName === "images/image4.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image4",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+function TestGetImageTiff()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image1.tiff",
+        function(fileName) {
+            TestEngine.test("Take picture image1.tiff : " + fileName,
+                            fileName === "images/image1.tiff" || fileName === "images/image1.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image1.tiff",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+function TestGetImageBMP()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image2.BMP",
+        function(fileName) {
+            TestEngine.test("Take picture image2.BMP : " + fileName,
+                            fileName === "images/image2.BMP" || fileName === "images/image2.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image2.BMP",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+function TestGetImageWrong()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image3.wrong",
+        function(fileName) {
+            TestEngine.test("Take picture image3.wrong : " + fileName,
+                            fileName === "images/image3.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image3.wrong",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+function TestGetImageXbm()
+{
+    var testObj = TestEngine.registerCallback(
+        "capture image4.xbm",
+        function(fileName) {
+            TestEngine.test("Take picture image4.xbm : " + fileName,
+                            fileName === "images/image4.xbm" || fileName === "images/image4.jpg");
+        },
+        onCameraError
+    );
+
+    try {
+        mainCamera.captureImage(
+            testObj.successCallback,
+            testObj.errorCallback,
+            {
+                destinationFilename:"images/image4.xbm",
+                highRes: false
+            }
+        );
+    } catch(e) {
+        TestEngine.test("Exception while capturing image", false);
+    }
+}
+
+//SimpleVideoTest();
+TestEngine.setTestSuiteName("Camera", 60000); // test suite timeout 60sec.
+
+TestEngine.addTest(true, TestGetCameras, "[Camera] Get cameras");
+//TestEngine.addTest(false, TestCaseCameraArrayProperties, "[Camera] Camera array properties");
+//TestEngine.addTest(false, TestJavaScript, "[Camera] JavaScript");
+//
+//TestEngine.addTest(false, TestCameraFunctionality_PreviewStart, "[Camera] Camrea preview start");
+//TestEngine.addTest(false, TestCameraFunctionality_TakePicture, "[Camera] Camrea picture");
+//TestEngine.addTest(false, TestCameraFunctionality_Video, "[Camera] Camrea video");
+//TestEngine.addTest(false, TestCameraFunctionality_PreviewStop, "[Camera] Camrea preview stop");
+//TestEngine.addTest(false, TestCameraCancel, "[Camera] Cancel take picture");
+//
+//TestEngine.addTest(false,TestGetCamerasNullErrorCallback, "Cam0014");
+//TestEngine.addTest(false,TestGetCamerasNullSuccessCallback, "Cam0015");
+//TestEngine.addTest(false,TestGetCamerasUndefinedSuccessCallback, "Cam0016");
+//TestEngine.addTest(false,TestGetCamerasNullCallbacks, "Cam0017");
+//TestEngine.addTest(false,TestGetCamerasNoErrorCallback, "Cam0018");
+//TestEngine.addTest(false,TestCameraId, "Cam0019");
+//TestEngine.addTest(false,TestCaptureImageNullOptions, "Cam0020");
+//TestEngine.addTest(false,TestCaptureImageUndefinedOptions, "Cam0021");
+//TestEngine.addTest(false,TestCaptureImageNullErrorCallback, "Cam0022");
+//TestEngine.addTest(false,TestCaptureImageNullSuccessCallback, "Cam0023");
+//TestEngine.addTest(false,TestCaptureImageUndefinedSuccessCallback, "Cam0024");
+//TestEngine.addTest(false,TestCaptureImageNullCallbacks, "Cam0025");
+//TestEngine.addTest(false,TestCaptureImageNoErrorCallback, "Cam0026");
+//TestEngine.addTest(false,TestCaptureImageInvalidFilename, "Cam0027");
+//TestEngine.addTest(false,TestCaptureImageInvalidHighRes, "Cam0028");
+//TestEngine.addTest(false,TestStartVideoCaptureNullOptions, "Cam0029");
+//TestEngine.addTest(false,TestStartVideoCaptureUndefinedOptions, "Cam0030");
+//TestEngine.addTest(false,TestStartVideoCaptureNullErrorCallback, "Cam0031");
+//TestEngine.addTest(false,TestStartVideoCaptureNullSuccessCallback, "Cam0032");
+//TestEngine.addTest(false,TestStartVideoCaptureUndefinedSuccessCallback, "Cam0033");
+//TestEngine.addTest(false,TestStartVideoCaptureNullCallbacks, "Cam0034");
+//TestEngine.addTest(false,TestStartVideoCaptureNoErrorCallback, "Cam0035");
+//TestEngine.addTest(false,TestStartVideoCaptureInvalidFilename, "Cam0036");
+//TestEngine.addTest(false,TestStartVideoCaptureInvalidHighRes, "Cam0037");
+//TestEngine.addTest(false,TestCreatePreviewNodeNullErrorCallback, "Cam0038");
+//TestEngine.addTest(false,TestCreatePreviewNodeNullSuccessCallback, "Cam0039");
+//TestEngine.addTest(false,TestCreatePreviewNodeUndefinedSuccessCallback, "Cam0040");
+//TestEngine.addTest(false,TestCreatePreviewNodeNullCallbacks, "Cam0041");
+//TestEngine.addTest(false,TestCreatePreviewNodeNoErrorCallback, "Cam0042");
+//
+//TestEngine.addTest(true, TestGetImageOK, "[CameraFileFormat] get image : image1.jpg");
+//TestEngine.addTest(true, TestGetImageOK2, "[CameraFileFormat] get image : image2.jpeg");
+//TestEngine.addTest(true, TestGetImagePnG, "[CameraFileFormat] get image : image3.PnG");
+//TestEngine.addTest(true, TestGetImageNoExt, "[CameraFileFormat] get image : image4");
+//TestEngine.addTest(true, TestGetImageTiff, "[CameraFileFormat] get image : image1.tiff");
+//TestEngine.addTest(true, TestGetImageBMP, "[CameraFileFormat] get image : image2.MBP");
+//TestEngine.addTest(true, TestGetImageWrong, "[CameraFileFormat] get image : image3.wrong");
+//TestEngine.addTest(true, TestGetImageXbm, "[CameraFileFormat] get image : image4.xbm");
+//=============================================================================
+
+function testNoExceptionWithMessage(message, fun) {
+  var testResult = true;
+  try {
+    fun();
+  }
+  catch (e) {
+    testResult = false;
+  }
+  TestEngine.test(message, testResult);
+}
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestContact.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestContact.js
new file mode 100644 (file)
index 0000000..6684368
--- /dev/null
@@ -0,0 +1,568 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function test_Contact_Presence() {
+    TestEngine.testPresence("Checking contact presence", deviceapis.pim.contact);
+}
+
+function test_Create_Contact_001() {
+    function AddressBooksCB001(addressbooks)
+    {
+        TestEngine.test("getAddressBooks success - fail expected", false);
+//        if(addressbooks.length > 0)
+//        {
+//            var addressbook = addressbooks[0];
+//            try{
+//                var contact = addressbook.createContact(
+//                                                        {
+//                                                        firstName:'Brad',
+//                                                        lastName:'Pitt'
+//                                                        });
+//
+//                TestEngine.test("check firstName", contact.firstName =="Brad");
+//                TestEngine.test("check lastName", contact.lastName =="Pitt");
+//            }
+//            catch(error)
+//            {
+//                TestEngine.logErr("createContact,error.code="+error.code);
+//            }
+//        }
+    }
+
+    function failCallback() {
+        TestEngine.test("getAddressBooks failed - as expected", true);
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB001,failCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_002() {
+    function AddressBooksCB002(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        addresses:[{types:['WORK'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Lushanlu, 1", postalCode:"210012", additionalInformation:"addinfo1"},
+                                                                        {types:['HOME'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Sanshanjie, 99", postalCode:"210009", additionalInformation:"addinfo2"}]
+                                                        });
+                TestEngine.test("check addresses length", contact.addresses.length == 2);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact, error="+error);
+            }
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB002,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_003() {
+    function AddressBooksCB003(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        phoneNumbers:[{number:'111111',types:['WORK']},
+                                                                    {number:'222222',types:['HOME']},
+                                                                    {number:'333333',types:['CAR']},
+                                                                    {number:'444444',types:['CELL']},
+                                                                    {number:'555555',types:['FAX']},
+                                                                    {number:'666666',types:['PAGER']},
+                                                                    {number:'7777777',types:['PREF']}]
+                                                                    });
+                TestEngine.test("check phoneNumbers length", contact.phoneNumbers.length == 7);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB003,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_004() {
+    function AddressBooksCB004(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        emails:[{email:"work@domain.com",types:['WORK']},
+                                                                {email:"home@domain.com",types:['HOME']},
+                                                                {email:"pref@domain.com",types:['PREF']}]
+                                                        });
+                TestEngine.test("check emails length", contact.emails.length == 3);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB004,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_005() {
+    function AddressBooksCB005(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        nicknames:['nickname1','nickname2','nickname3','nickname4']
+                                                        });
+                TestEngine.test("check nicknames length", contact.nicknames.length == 4);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB005,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_006() {
+    function AddressBooksCB006(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        photoURI:'/opt/apps/widget/tests/attachments/attach1.jpg'
+                                                        });
+                TestEngine.test("check photoURI", contact.photoURI == "/opt/apps/widget/tests/attachments/attach1.jpg");
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB006,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Create_Contact_007() {
+    function AddressBooksCB007(addressbooks)
+    {
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        firstName:'Brad',
+                                                        lastName:'Pitt',
+                                                        addresses:[{types:['WORK'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Lushanlu, 1", postalCode:"210012", additionalInformation:"addinfo1"},
+                                                                        {types:['HOME'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Sanshanjie, 99", postalCode:"210009", additionalInformation:"addinfo2"}],
+                                                        phoneNumbers:[{number:'111111',types:['WORK']},
+                                                                    {number:'222222',types:['HOME']},
+                                                                    {number:'333333',types:['CAR']},
+                                                                    {number:'444444',types:['CELL']},
+                                                                    {number:'555555',types:['FAX']},
+                                                                    {number:'666666',types:['PAGER']},
+                                                                    {number:'7777777',types:['PREF']}],
+                                                        emails:[{email:"work@domain.com",types:['WORK']},
+                                                                {email:"home@domain.com",types:['HOME']},
+                                                                {email:"pref@domain.com",types:['PREF']}],
+                                                        nicknames:['nickname1','nickname2','nickname3','nickname4']
+                                                        });
+                TestEngine.test("check firstName", contact.firstName =="Brad");
+                TestEngine.test("check lastName", contact.lastName =="Pitt");
+                TestEngine.test("check addresses length", contact.addresses.length == 2);
+                TestEngine.test("check phoneNumbers length", contact.phoneNumbers.length == 7);
+                TestEngine.test("check emails length", contact.emails.length == 3);
+                TestEngine.test("check nicknames length", contact.nicknames.length == 4);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",AddressBooksCB007,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Get_AddressBooks_001() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.logOK("getAddressBooksCB");
+        TestEngine.log("addressbooks length = " + addressbooks.length);
+
+        for(var i=0;i<addressbooks.length;i++)
+        {
+            TestEngine.log(addressbooks[i].name);
+            TestEngine.log(addressbooks[i].type);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_Add_Contact_006() {
+    function AddressBooksCB013(addressbooks)
+    {
+        var contact;
+        TestEngine.log("AddressBooksCB");
+
+        if(addressbooks.length > 0)
+        {
+            var addressbook = addressbooks[0];
+            TestEngine.log("The addressbook type is " + addressbook.type +  " and name " + addressbook.name);
+
+            try{
+                var contact = addressbook.createContact(
+                                                        {
+                                                        firstName:'Brad',
+                                                        lastName:'Pitt',
+                                                        addresses:[{types:['PREF'],country:"Finland",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Sanshanjie, 99", postalCode:"210009", additionalInformation:"Other"},
+                                                                        {types:['HOME'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Sanshanjie, 99", postalCode:"210009", additionalInformation:"Home"},
+                                                                        {types:['WORK'],country:"China",region:"Jiangsu",city:"Nanjing",county:"None",streetAddress:"Lushanlu, 1", postalCode:"210012", additionalInformation:"Work"}],
+                                                        phoneNumbers:[{number:'111111',types:['WORK']},
+                                                                    {number:'222222',types:['HOME']},
+                                                                    {number:'333333',types:['CAR']},
+                                                                    {number:'444444',types:['CELL']},
+                                                                    {number:'555555',types:['FAX']},
+                                                                    {number:'666666',types:['PAGER']},
+                                                                    {number:'7777777',types:['PREF']}],
+                                                        emails:[{email:"work@domain.com",types:['WORK']},
+                                                                {email:"home@domain.com",types:['HOME']},
+                                                                {email:"pref@domain.com",types:['PREF']}],
+                                                        nicknames:['nickname1','nickname2','nickname3','nickname4'],
+                                                        photoURI:'/opt/apps/widget/tests/attachments/attach1.jpg'
+                                                        });
+                var callback=TestEngine.registerCallback("addContact",contactAddedCB,addContactErrorCallback);
+                addressbook.addContact(callback.successCallback, callback.errorCallback, contact);
+            }
+            catch(error)
+            {
+                TestEngine.logErr("createContact,error.code="+error.code);
+            }
+        }
+    }
+    deviceapis.pim.contact.getAddressBooks(AddressBooksCB013,  getAddressBooksErrorCallback);
+}
+
+
+function test_findContacts_001() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback);
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_findContacts_002() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback,{firstName:'%ra%'});
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_findContacts_003() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback,{lastName:'%itt%'});
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_findContacts_004() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback,{phoneNumbers:[{number:'111111',types:['WORK']}]});
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_findContacts_005() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback,{addresses:[{types:['WORK'],country:"China"}]});
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_findContacts_006() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",contactSearchSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback,{emails:[{email:"work@domain.com%",types:['WORK']}]});
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_deleteContacts_001() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        function findContactSuccessCallback(contacts)
+        {
+            TestEngine.log("findContactSuccessCallback");
+            TestEngine.test("Contact list not empty", contacts.length > 0);
+            function contactDeleteSuccessCallback()
+            {
+                TestEngine.logOK("contactDeleteSuccessCallback Callback");
+            }
+
+            var callback3=TestEngine.registerCallback("deleteContacts",contactDeleteSuccessCallback,deleteContactErrorCallback);
+            addressbooks[0].deleteContact(callback3.successCallback, callback3.errorCallback, contacts[0].id);
+        }
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",findContactSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback);
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function test_updateContacts_001() {
+    function getAddressBooksCB(addressbooks)
+    {
+        TestEngine.log("getAddressBooksCB");
+        //var addressbook = addressbooks[0];
+
+        function findContactSuccessCallback(contacts)
+        {
+            TestEngine.log("findContactSuccessCallback");
+            function contactUpdateSuccessCallback()
+            {
+                TestEngine.logOK("contactUpdateSuccessCallback Callback");
+            }
+            TestEngine.test("Contact list not empty", contacts.length > 0);
+            TestEngine.log("contacts[0] id ="+contacts[0].id );
+            contacts[0].firstName = "Asuka3";
+            contacts[0].lastName = "Langley3";
+            contacts[0].photoURI= "/opt/apps/widget/tests/attachments/attach1.jpg";
+            var phoneNumber ={number:'999999',types:['WORK']};
+            var address = {types:['HOME'],country:"Test",region:"Test",city:"Test",county:"Test",streetAddress:"Test", postalCode:"Test", additionalInformation:"Test"};
+            var email={email:"test@domain.com",types:['WORK']};
+
+            TestEngine.log("photoURI =" + contacts[0].photoURI);
+            if(contacts[0].phoneNumbers.length>0)
+            {
+                contacts[0].phoneNumbers[0]=phoneNumber;
+            }
+
+            if(contacts[0].addresses.length>0)
+            {
+                contacts[0].addresses[0]=address;
+            }
+
+            if(contacts[0].emails.length>0)
+            {
+                contacts[0].emails[0]=email;
+            }
+
+            var callback3=TestEngine.registerCallback("updateContact",contactUpdateSuccessCallback,updateContactErrorCallback);
+            addressbooks[0].updateContact(callback3.successCallback, callback3.errorCallback, contacts[0]);
+        }
+
+        try{
+            var callback2=TestEngine.registerCallback("findContacts",findContactSuccessCallback,findContactErrorCallback);
+            addressbooks[0].findContacts(callback2.successCallback, callback2.errorCallback);
+        }
+        catch(error)
+        {
+            TestEngine.logErr("createContact,error.code="+error.code);
+        }
+    }
+
+    var callback=TestEngine.registerCallback("getAddressBooks",getAddressBooksCB,getAddressBooksErrorCallback);
+    deviceapis.pim.contact.getAddressBooks(callback.successCallback, callback.errorCallback);
+}
+
+function contactAddedCB(contact)
+{
+    TestEngine.log("typeof(contact) =" + typeof(contact));
+    TestEngine.testPresence("Checking contact presence", contact);
+    TestEngine.test("check firstName", contact.firstName =="Brad");
+    TestEngine.test("check lastName", contact.lastName =="Pitt");
+    TestEngine.test("check addresses length", contact.addresses.length == 3);
+    TestEngine.test("check phoneNumbers length", contact.phoneNumbers.length == 7);
+    TestEngine.test("check emails length", contact.emails.length == 3);
+    //TestEngine.test("check nicknames length", contact.nicknames.length == 4);
+    TestEngine.test("check photoURI", contact.photoURI == "/opt/apps/widget/tests/attachments/attach1.jpg");
+    TestEngine.logOK("contactAddedCB Callback");
+}
+
+function contactSearchSuccessCallback(contacts)
+{
+    TestEngine.log(""+contacts.length + " results found.");
+    for(var i=0;i<contacts.length;i++)
+    {
+        TestEngine.log("contacts["+i+"] id=" + contacts[i].id);
+        TestEngine.log("contacts["+i+"] firstName=" + contacts[i].firstName);
+        TestEngine.log("contacts["+i+"] lastName=" + contacts[i].lastName);
+        TestEngine.log("contacts["+i+"] addresses length=" + contacts[i].addresses.length);
+        TestEngine.log("contacts["+i+"] phoneNumbers length=" + contacts[i].phoneNumbers.length);
+        TestEngine.log("contacts["+i+"] emails length =" + contacts[i].emails.length );
+        TestEngine.log("contacts["+i+"] nicknames length=" + contacts[i].nicknames.length);
+    }
+    TestEngine.logOK("contactAddedCB Callback");
+
+}
+
+function getAddressBooksErrorCallback(response)
+{
+    TestEngine.logErr("getAddressBooks Error Callback");
+}
+
+function addContactErrorCallback(response)
+{
+    TestEngine.logErr("contactAddedCB Callback");
+}
+
+function findContactErrorCallback(response)
+{
+    TestEngine.logErr("find contact error Callback");
+}
+
+function deleteContactErrorCallback(response)
+{
+    TestEngine.logErr("Delete contact error Callback");
+}
+
+function updateContactErrorCallback(response)
+{
+    TestEngine.logErr("Update contact error Callback");
+}
+
+TestEngine.setTestSuiteName('[WAC2.0][Contact]',60*1000);
+//TestEngine.addTest(true,test_Contact_Presence,"[WAC2.0][Contact]test_Contact");
+TestEngine.addTest(true,test_Create_Contact_001,"[WAC2.0][Contact]test_Create_Contact_001");
+//TestEngine.addTest(true,test_Create_Contact_002,"[WAC2.0][Contact]test_Create_Contact_002");
+//TestEngine.addTest(true,test_Create_Contact_003,"[WAC2.0][Contact]test_Create_Contact_003");
+//TestEngine.addTest(true,test_Create_Contact_004,"[WAC2.0][Contact]test_Create_Contact_004");
+//TestEngine.addTest(true,test_Create_Contact_005,"[WAC2.0][Contact]test_Create_Contact_005");
+//TestEngine.addTest(true,test_Create_Contact_006,"[WAC2.0][Contact]test_Create_Contact_006");
+//TestEngine.addTest(true,test_Create_Contact_007,"[WAC2.0][Contact]test_Create_Contact_007");
+//
+//TestEngine.addTest(true,test_Add_Contact_006,"[WAC2.0][Contact]test_Add_Contact_006");
+//TestEngine.addTest(true,test_Get_AddressBooks_001,"[WAC2.0][Contact]test_Get_AddressBooks_001");
+//TestEngine.addTest(true,test_findContacts_001,"[WAC2.0][Contact]test_Find_findContacts_001");
+//TestEngine.addTest(true,test_findContacts_002,"[WAC2.0][Contact]test_Find_findContacts_002");
+//TestEngine.addTest(true,test_findContacts_003,"[WAC2.0][Contact]test_Find_findContacts_003");
+//TestEngine.addTest(true,test_findContacts_004,"[WAC2.0][Contact]test_Find_findContacts_004");
+//TestEngine.addTest(true,test_findContacts_005,"[WAC2.0][Contact]test_Find_findContacts_005");
+//TestEngine.addTest(true,test_findContacts_006,"[WAC2.0][Contact]test_Find_findContacts_006");
+//TestEngine.addTest(true,test_updateContacts_001,"[WAC2.0][Contact]test_Find_updateContacts_001");
+//TestEngine.addTest(true,test_deleteContacts_001,"[WAC2.0][Contact]test_Find_deleteContacts_001");
+
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestDeviceInteraction.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestDeviceInteraction.js
new file mode 100644 (file)
index 0000000..32dd6e3
--- /dev/null
@@ -0,0 +1,234 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of deviceinteraction plugin tests.
+ *
+ * @author      Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version     0.1
+ */
+
+var di = deviceapis.deviceinteraction;
+var filename = "wgt-package/icon.png"
+var filename2 = "wgt-package/attachments/attach1.jpg"
+var badFilename1 = "config.xml"
+var badFilename2 = ""
+var badFilename3 = "/opt/media/Sounds and music/Music/Because of you.mp3"
+
+// callbacks
+
+function expectedSuccess()
+{
+    TestEngine.test("expectedSuccess callback",true);
+    di.stopNotify();
+    di.stopVibrate();
+};
+
+function expectedFailure()
+{
+    TestEngine.test("expectedFailure callback",true);
+};
+
+function unexpectedSuccess()
+{
+    TestEngine.test("unexpectedSuccess callback",false);
+};
+
+function unexpectedFailure()
+{
+    TestEngine.test("unexpectedFailure callback",false);
+};
+
+// tests
+
+function test_deviceinteraction_presence_001()
+{
+    TestEngine.testPresence("Checking deviceapis presence", deviceapis);
+    TestEngine.testPresence2(deviceapis, 'deviceinteraction');
+}
+
+function test_deviceinteraction_functions_002()
+{
+    var props = new Array();
+    props.push(new Array('startNotify', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('stopNotify', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('startVibrate', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('stopVibrate', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('lightOn', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('lightOff', null, null, false, TestEngine.FUNCTION));
+    props.push(new Array('setWallpaper', null, null, false, TestEngine.FUNCTION));
+    TestEngine.testProperties(di, props);
+}
+
+function test_deviceinteraction_startNotify_003()
+{
+    check_ulong("startNotify");
+    di.stopNotify();
+
+    try
+    {
+        var cbObj = TestEngine.registerCallback("test", expectedSuccess, unexpectedFailure);
+        di.startNotify(cbObj.successCallback, cbObj.errorCallback, 2000);
+        TestEngine.test("No error thrown from startNotify", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_stopNotify_004()
+{
+    try
+    {
+        di.stopNotify();
+        TestEngine.test("No error thrown from stopNotify", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_startVibrate_005()
+{
+    check_ulong("startVibrate");
+    di.stopVibrate();
+
+    try
+    {
+//        var cbObj = TestEngine.registerCallback("test", expectedSuccess, unexpectedFailure);
+        var cbObj = TestEngine.registerCallback("test", unexpectedFailure, expectedSuccess);
+        di.startVibrate(cbObj.successCallback, cbObj.errorCallback, 2000);
+        TestEngine.test("No error thrown from startVibrate", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_stopVibrate_006()
+{
+    try
+    {
+        di.stopVibrate();
+        TestEngine.test("No error thrown from stopVibrate", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_lightOn_008()
+{
+    check_ulong("lightOn", 2000);
+    di.lightOff();
+    try
+    {
+        var cbObj = TestEngine.registerCallback("test", expectedSuccess, unexpectedFailure);
+        di.lightOn(cbObj.successCallback, cbObj.errorCallback, 2000);
+        TestEngine.test("No error thrown from lightOn", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_lightOff_009()
+{
+    try
+    {
+        di.lightOff();
+        TestEngine.test("No error thrown from lightOff", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function test_deviceinteraction_setWallpaper_010()
+{
+    TestEngine.log("Checking function: deviceinteaction.setWallpaper(cb, cb, string)");
+
+    var cbObj1 = TestEngine.registerCallback("setWallpaper", expectedSuccess, unexpectedFailure);
+    di.setWallpaper(cbObj1.successCallback, cbObj1.errorCallback, filename);
+
+    var cbObj2 = TestEngine.registerCallback("setWallpaper", unexpectedSuccess, expectedFailure);
+    di.setWallpaper(undefined, cbObj2.errorCallback, filename);
+
+    TestEngine.catchErrorType("code", 17, di, "setWallpaper", 1234, unexpectedFailure, filename);
+
+    var cbObj3 = TestEngine.registerCallback("setWallpaper", expectedSuccess, unexpectedFailure);
+    di.setWallpaper(cbObj3.successCallback, undefined, filename);
+
+    TestEngine.catchErrorType("code", 17, di, "setWallpaper", unexpectedSuccess, 1234, filename);
+
+    var cbObj4 = TestEngine.registerCallback("setWallpaper", unexpectedSuccess, expectedFailure);
+    di.setWallpaper(cbObj4.successCallback, cbObj4.errorCallback, undefined);
+
+    var cbObj5 = TestEngine.registerCallback("setWallpaper", unexpectedSuccess, expectedFailure);
+    di.setWallpaper(cbObj5.successCallback, cbObj5.errorCallback, 1234);
+
+    var cbObj6 = TestEngine.registerCallback("setWallpaper", unexpectedSuccess, expectedFailure);
+    di.setWallpaper(null, cbObj6.errorCallback, filename);
+
+    var cbObj7 = TestEngine.registerCallback("setWallpaper", expectedSuccess, unexpectedFailure);
+    di.setWallpaper(cbObj7.successCallback, null, filename2);
+
+    var cbObj8 = TestEngine.registerCallback("setWallpaper", unexpectedSuccess, expectedFailure);
+    di.setWallpaper(cbObj8.successCallback, cbObj8.errorCallback, null);
+}
+
+function check_ulong(func)
+{
+    TestEngine.log("Checking function: deviceinteaction." + func + "(unsigned long)");
+
+    TestEngine.catchErrorType("code", 17, di, func, expectedSuccess, unexpectedFailure);
+
+    var cbObj1 = TestEngine.registerCallback("null param", expectedSuccess, unexpectedFailure);
+    di[func](cbObj1.successCallback, cbObj1.errorCallback, null);
+
+    var cbObj2 = TestEngine.registerCallback("undefined param", expectedSuccess, unexpectedFailure);
+    di[func](cbObj2.successCallback, cbObj2.errorCallback, undefined);
+
+    var cbObj3 = TestEngine.registerCallback("undefined param", unexpectedSuccess, expectedFailure);
+    di[func](cbObj3.successCallback, cbObj3.errorCallback, -666);
+
+    var cbObj4 = TestEngine.registerCallback("undefined param", expectedSuccess, unexpectedFailure);
+    di[func](cbObj4.successCallback, cbObj4.errorCallback, "test");
+
+    var cbObj5 = TestEngine.registerCallback("undefined param", expectedSuccess, unexpectedFailure);
+    di[func](cbObj5.successCallback, cbObj5.errorCallback, new Date());
+
+    var cbObj6 = TestEngine.registerCallback("undefined param", expectedSuccess, unexpectedFailure);
+    di[func](cbObj6.successCallback, cbObj6.errorCallback, [6, 6, 6]);
+}
+
+//=============================================================================
+TestEngine.setTestSuiteName('[WAC2.0][DeviceInteractionManager]', 10*1000);
+//TestEngine.addTest(true,test_deviceinteraction_presence_001, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_presence_001");
+//TestEngine.addTest(true,test_deviceinteraction_functions_002, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_functions_002");
+//TestEngine.addTest(true,test_deviceinteraction_startNotify_003, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_startNotify_003");
+//TestEngine.addTest(true,test_deviceinteraction_stopNotify_004, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_stopNotify_004");
+TestEngine.addTest(true,test_deviceinteraction_startVibrate_005, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_startVibrate_005");
+//TestEngine.addTest(true,test_deviceinteraction_stopVibrate_006, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_stopVibrate_006");
+//TestEngine.addTest(true,test_deviceinteraction_lightOn_008, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_lightOn_008");
+//TestEngine.addTest(true,test_deviceinteraction_lightOff_009, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_lightOff_009");
+//TestEngine.addTest(true,test_deviceinteraction_setWallpaper_010, "[WAC2.0][DeviceInteractionManager]test_deviceinteraction_setWallpaper_010");
+//=============================================================================
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestDevicestatus.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestDevicestatus.js
new file mode 100644 (file)
index 0000000..ef55610
--- /dev/null
@@ -0,0 +1,1159 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test contact class.
+ *
+ * @author      Pawel Misiak (p.misiak@samsung.com)
+ * @author      Shi Hezhang (hezhang.shi@samsung.com)
+ * @version     0.1
+ */
+
+var DevStatusObj = deviceapis.devicestatus;
+
+var aspectsProperty=Object();
+aspectsProperty['Battery']=['batteryLevel', 'batteryBeingCharged'];
+aspectsProperty['CellularHardware']=['status'];
+aspectsProperty['CellularNetwork']=['isInRoaming', 'signalStrength', 'operatorName'];
+aspectsProperty['Device']=['imei', 'model', 'version', 'vendor'];
+aspectsProperty['Display']=['resolutionHeight', 'pixelAspectRatio', 'dpiY', 'resolutionWidth', 'dpiX', 'colorDepth'];
+aspectsProperty['MemoryUnit']=['size', 'removable', 'availableSize'];
+aspectsProperty['OperatingSystem']=['language', 'version', 'name', 'vendor'];
+aspectsProperty['WebRuntime']=['wacVersion', 'supportedImageFormats', 'version', 'name', 'vendor'];
+aspectsProperty['WiFiHardware']=['status'];
+aspectsProperty['WiFiNetwork']=['ssid', 'signalStrength', 'networkStatus'];
+
+var wrongProperty=['', 'abc'];
+
+var aspectsComponent=Object();
+aspectsComponent['Battery']=['_default'];
+aspectsComponent['CellularHardware']=['_default'];
+aspectsComponent['CellularNetwork']=['_default'];
+aspectsComponent['Device']=['_default'];
+aspectsComponent['Display']=['_default', '_active'];
+aspectsComponent['MemoryUnit']=['_default'];
+aspectsComponent['OperatingSystem']=['_active', '_default'];
+aspectsComponent['WebRuntime']=['_active', '_default'];
+aspectsComponent['WiFiHardware']=['_default'];
+aspectsComponent['WiFiNetwork']=['_default'];
+
+//callbacks;
+function emptyCallback() {
+    jsPrint("empty callback");
+}
+
+function onValueRetrieved(value) {
+    jsPrint("!!!!! value=" + value);
+    TestEngine.test("return value is valid", (value != null));
+}
+
+function onError (error) {
+    TestEngine.test("onError", false);
+}
+
+//DevStatus001;
+function presenceTest()
+{
+    TestEngine.test("Checking deviceapis object", deviceapis);
+    TestEngine.test("Checking Devicestatus object", DevStatusObj);
+
+    TestEngine.test("Checking type of getComponents", isFunction(DevStatusObj.getComponents));
+    TestEngine.test("Checking type of isSupported", isFunction(DevStatusObj.isSupported));
+    TestEngine.test("Checking type of getPropertyValue", isFunction(DevStatusObj.getPropertyValue));
+    TestEngine.test("Checking type of watchPropertyChange", isFunction(DevStatusObj.watchPropertyChange));
+    TestEngine.test("Checking type of clearPropertyChange", isFunction(DevStatusObj.clearPropertyChange));
+}
+
+//DevStatus002;
+function getCompomentInvalidParametersTest() {
+    TestEngine.catchErrorType("code", 17, DevStatusObj, "getComponents");
+
+    try {
+        DevStatusObj.getComponents(undefined);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getComponents(null);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getComponents(1234);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+}
+
+//DevStatus003;
+function isSupportedInvalidParametersTest() {
+    TestEngine.catchErrorType("code", 17, DevStatusObj, "isSupported");
+    try {
+        var stat = DevStatusObj.isSupported(undefined);
+        TestEngine.test("exception should not be thrown", stat == false);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        var stat = DevStatusObj.isSupported(null);
+        TestEngine.test("exception should not be thrown", stat == false);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        var stat = DevStatusObj.isSupported(1234);
+        TestEngine.test("exception should not be thrown", stat == false);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        jsPrint("e.code=" + e.code);
+        TestEngine.test("exception catched", false);
+    }
+}
+
+//DevStatus004;
+function getPropertyValueInvalidArgumentsTest() {
+    var onInvalidValueError = function (error) {
+        TestEngine.test("INVALID_VALUES_ERR", error.code == error.INVALID_VALUES_ERR);
+    }
+    var failedSuccess = function (value) {
+        TestEngine.logErr("Success should not be called");
+    }
+    var cbObjInvalidErr = TestEngine.registerCallback("BatterybatteryLeveltest",
+        failedSuccess,
+        onInvalidValueError,
+        6);
+
+    try {
+        DevStatusObj.getPropertyValue(null, null,{
+            property:"batteryLevel",
+            aspect:"Battery"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(null, cbObjInvalidErr.errorCallback,{
+            property:"batteryLevel",
+            aspect:"Battery"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(cbObjInvalidErr.successCallback, cbObjInvalidErr.errorCallback, 1);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(cbObjInvalidErr.successCallback, cbObjInvalidErr.errorCallback, {
+            property:"batteryLevel"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(cbObjInvalidErr.successCallback, cbObjInvalidErr.errorCallback, {
+            property:"batteryLevel",
+            aspect:"invalid"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(cbObjInvalidErr.successCallback, cbObjInvalidErr.errorCallback, {
+            aspect:"invalid"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.getPropertyValue(cbObjInvalidErr.successCallback, cbObjInvalidErr.errorCallback, {
+            invalid1:"",
+            invalid2:""
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+}
+
+//DevStatus005;
+function watchPropertyChangeInvalidParametersTest() {
+
+    var callbackFunction = function (value) {
+        TestEngine.test("SuccessCallback should not be thrown", false);
+    }
+    var onSuccessError = function(err) {
+        TestEngine.logOK("Error: " + err.code);
+        TestEngine.test("Error callback called as expected", true);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(callbackFunction, onSuccessError, 1);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(null, null, 1);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(callbackFunction, onSuccessError, {
+            property:"batteryLevel"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(callbackFunction, onSuccessError, {
+            property:"batteryLevel",
+            aspect:"invalid"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(callbackFunction, onSuccessError, {
+            invalid:"batteryLevel",
+            invalid:"Battery"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.watchPropertyChange(callbackFunction, onSuccessError, {
+            property:"invalid",
+            aspect:"invalid"
+        });
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+}
+
+//DevStatus006;
+function clearPropertyChangeInvalidParametersTest() {
+    var callbackFunction = function (value) {
+        TestEngine.logErr("Function called as watch id ???", false);
+    }
+
+    try {
+        DevStatusObj.clearPropertyChange("invalid int value");
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+
+    try {
+        DevStatusObj.clearPropertyChange(callbackFunction);
+        TestEngine.test("exception should be thrown", false);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", e.code==e.TYPE_MISMATCH_ERR);
+    }
+
+    try {
+        DevStatusObj.clearPropertyChange(11111111);
+        TestEngine.test("exception should not be thrown", true);
+    } catch(e) {
+        jsPrint("e.message=" + e.message);
+        TestEngine.test("exception catched", false);
+    }
+}
+
+//DevStatus007;
+function getComponentsTest() {
+    for (var aspect in aspectsComponent) {
+        var retComponent = DevStatusObj.getComponents(aspect);
+        aspectsComponent[aspect].sort();
+        retComponent.sort();
+        jsPrint("retComponent=" + retComponent);
+        jsPrint("aspectsComponent[aspect]="+aspectsComponent[aspect]);
+        TestEngine.test("length of component for aspect = " + aspect + "is proper", retComponent.length == aspectsComponent[aspect].length);
+
+        for (var i =0; i<retComponent.length; i++) {
+            TestEngine.test("component for aspect " + aspect + " table is equal", retComponent[i] == aspectsComponent[aspect][i]);
+        }
+    }
+}
+
+//DevStatus008;
+function isSupportedTest() {
+    //aspect check;
+    for (var aspect in aspectsProperty) {
+        TestEngine.test("Aspect " + aspect + " check", DevStatusObj.isSupported(aspect));
+    }
+    TestEngine.test("Aspect empty check", !DevStatusObj.isSupported(""));
+    TestEngine.test("Aspect random abc check", !DevStatusObj.isSupported("abc"));
+
+    //aspect and property check;
+    for (var aspect in aspectsProperty) {
+        for (var property in aspectsProperty[aspect]) {
+            var propertyName = aspectsProperty[aspect][property];
+            TestEngine.test("Aspect " + aspect + "/" + propertyName + " check", DevStatusObj.isSupported(aspect, propertyName));
+        }
+        TestEngine.test("Aspect " + aspect + "/null check", DevStatusObj.isSupported(aspect, null));
+    }
+
+    //aspect and wrong property check;
+    for (var aspect in aspectsProperty) {
+        for (var property in wrongProperty) {
+            var propertyName = wrongProperty[property];
+            TestEngine.test("Wrong aspect " + aspect + "/" + propertyName  + " check", !DevStatusObj.isSupported(aspect, propertyName ));
+        }
+    }
+}
+
+//DevStatus009-1;
+function getPropertyValueTest1a() {
+    var cbObj = TestEngine.registerCallback("BatterybatteryLeveltest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"batteryLevel",
+            aspect:"Battery"
+        }
+        );
+}
+
+//DevStatus009-1;
+function getPropertyValueTest1b() {
+    var cbObj = TestEngine.registerCallback("BatterybatteryBeingChargedtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"batteryBeingCharged",
+            aspect:"Battery"
+        }
+        );
+}
+
+//DevStatus009-2;
+function getPropertyValueTest2a() {
+    var cbObj = TestEngine.registerCallback("CellularHardwarestatustest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"status",
+            aspect:"CellularHardware"
+        }
+        );
+}
+
+//DevStatus009-3;
+function getPropertyValueTest3a() {
+    var cbObj = TestEngine.registerCallback("CellularNetworkisInRoamingtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"isInRoaming",
+            aspect:"CellularNetwork"
+        }
+        );
+}
+
+//DevStatus009-2;
+function getPropertyValueTest3b() {
+    var cbObj = TestEngine.registerCallback("CellularNetworksignalStrengthtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"signalStrength",
+            aspect:"CellularNetwork"
+        }
+        );
+}
+
+//DevStatus009-2;
+function getPropertyValueTest3c() {
+    var cbObj = TestEngine.registerCallback("CellularNetworkoperatorNametest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"operatorName",
+            aspect:"CellularNetwork"
+        }
+        );
+}
+
+//DevStatus009-4;
+function getPropertyValueTest4a() {
+    var cbObj = TestEngine.registerCallback("Deviceimeitest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"imei",
+            aspect:"Device"
+        }
+        );
+}
+
+//DevStatus009-4;
+function getPropertyValueTest4b() {
+    var cbObj = TestEngine.registerCallback("Devicemodeltest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"model",
+            aspect:"Device"
+        }
+        );
+}
+
+//DevStatus009-4;
+function getPropertyValueTest4c() {
+    var cbObj = TestEngine.registerCallback("Deviceversiontest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"version",
+            aspect:"Device"
+        }
+        );
+}
+
+//DevStatus009-4;
+function getPropertyValueTest4d() {
+    var cbObj = TestEngine.registerCallback("Devicevendortest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"vendor",
+            aspect:"Device"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5a() {
+    var cbObj = TestEngine.registerCallback("DisplayresolutionHeighttest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"resolutionHeight",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5b() {
+    var cbObj = TestEngine.registerCallback("DisplaypixelAspectRatiotest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"pixelAspectRatio",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5c() {
+    var cbObj = TestEngine.registerCallback("DisplaydpiYtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"dpiY",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5d() {
+    var cbObj = TestEngine.registerCallback("DisplayresolutionWidthtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"resolutionWidth",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5e() {
+    var cbObj = TestEngine.registerCallback("DisplaydpiXtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"dpiX",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-5;
+function getPropertyValueTest5f() {
+    var cbObj = TestEngine.registerCallback("DisplaycolorDepthtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"colorDepth",
+            aspect:"Display"
+        }
+        );
+}
+
+//DevStatus009-6;
+function getPropertyValueTest6a() {
+    var cbObj = TestEngine.registerCallback("MemoryUnitsizetest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"size",
+            aspect:"MemoryUnit"
+        }
+        );
+}
+
+//DevStatus009-6;
+function getPropertyValueTest6b() {
+    var cbObj = TestEngine.registerCallback("MemoryUnitremovabletest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"removable",
+            aspect:"MemoryUnit"
+        }
+        );
+}
+
+//DevStatus009-6;
+function getPropertyValueTest6c() {
+    var cbObj = TestEngine.registerCallback("MemoryUnitavailableSizetest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"availableSize",
+            aspect:"MemoryUnit"
+        }
+        );
+}
+
+//DevStatus009-7;
+function getPropertyValueTest7a() {
+    var cbObj = TestEngine.registerCallback("OperatingSystemlanguagetest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"language",
+            aspect:"OperatingSystem"
+        }
+        );
+}
+
+//DevStatus009-7;
+function getPropertyValueTest7b() {
+    var cbObj = TestEngine.registerCallback("OperatingSystemversiontest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"version",
+            aspect:"OperatingSystem"
+        }
+        );
+}
+
+//DevStatus009-7;
+function getPropertyValueTest7c() {
+    var cbObj = TestEngine.registerCallback("OperatingSystemnametest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"name",
+            aspect:"OperatingSystem"
+        }
+        );
+}
+
+//DevStatus009-7;
+function getPropertyValueTest7d() {
+    var cbObj = TestEngine.registerCallback("OperatingSystemvendortest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"vendor",
+            aspect:"OperatingSystem"
+        }
+        );
+}
+
+//DevStatus009-8;
+function getPropertyValueTest8a() {
+    var cbObj = TestEngine.registerCallback("WebRuntimeversiontest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"version",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+//DevStatus009-8;
+function getPropertyValueTest8b() {
+    var cbObj = TestEngine.registerCallback("WebRuntimenametest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"name",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+//DevStatus009-8;
+function getPropertyValueTest8c() {
+    var cbObj = TestEngine.registerCallback("WebRuntimevendortest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"vendor",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+//DevStatus009-8;
+function getPropertyValueTest8d() {
+    var cbObj = TestEngine.registerCallback("WebRuntimewacVersiontest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"wacVersion",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+//DevStatus009-8;
+function getPropertyValueTest8e() {
+    var cbObj = TestEngine.registerCallback("WebRuntimesupportedImageFormatstest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"supportedImageFormats",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+//DevStatus009-9;
+function getPropertyValueTest9a() {
+    var cbObj = TestEngine.registerCallback("WiFiHardwarestatustest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"status",
+            aspect:"WiFiHardware"
+        }
+        );
+}
+
+//DevStatus009-10;
+function getPropertyValueTest10a() {
+    var cbObj = TestEngine.registerCallback("WiFiNetworkssidtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"ssid",
+            aspect:"WiFiNetwork"
+        }
+        );
+}
+
+//DevStatus009-10;
+function getPropertyValueTest10b() {
+    var cbObj = TestEngine.registerCallback("WiFiNetworksignalStrengthtest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"signalStrength",
+            aspect:"WiFiNetwork"
+        }
+        );
+}
+
+//DevStatus009-10;
+function getPropertyValueTest10c() {
+    var cbObj = TestEngine.registerCallback("WiFiNetworknetworkStatustest",
+        onValueRetrieved,
+        onError
+        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"networkStatus",
+            aspect:"WiFiNetwork"
+        }
+        );
+}
+
+function onCellidRetrieved(value) {
+    jsPrint("!!!!! mcc=" + value.mcc);
+    jsPrint("!!!!! mnc=" + value.mnc);
+    jsPrint("!!!!! cellid=" + value.cellid);
+    jsPrint("!!!!! lac=" + value.lac);
+    jsPrint("!!!!! rat=" + value.rat);
+    TestEngine.test("success callback executed", (value != null));
+}
+
+function acceptError(){
+    TestEngine.test("Error occure as expected", true);
+}
+
+function rejectSuccess(){
+    TestEngine.test("Success - error expected", false);
+}
+
+//DevStatus-extra;
+function getPropertyValueTestCellid() {
+    var cbObj = TestEngine.registerCallback("CellularNetworkcellidtest",
+        rejectSuccess,
+        acceptError);
+//    var cbObj = TestEngine.registerCallback("CellularNetworkcellidtest",
+//        onCellidRetrieved,
+//        onError
+//        );
+
+    DevStatusObj.getPropertyValue(
+        cbObj.successCallback, cbObj.errorCallback,
+        {
+            property:"cellid",
+            aspect:"CellularNetwork"
+        }
+        );
+}
+
+//DevStatus010;
+function watchClearPropertyChangeTest() {
+    var watcherId1 = 0;
+    var watcherId2 = 0;
+    var watcherId3 = 0;
+
+    var callbackFunction1 = function (value) {
+        TestEngine.test("Callback 1 called: " +value, true);
+        DevStatusObj.clearPropertyChange(watcherId1);
+
+    }
+    var callbackFunction2 = function (value) {
+        TestEngine.test("Callback 2 called: " +value, true);
+        DevStatusObj.clearPropertyChange(watcherId2);
+
+    }
+    var callbackFunction3 = function (value) {
+        TestEngine.test("Callback 3 called: " +value, true);
+        DevStatusObj.clearPropertyChange(watcherId3);
+    }
+
+    var call1 = TestEngine.registerCallback("watchPropertyCallback1", callbackFunction1, onError);
+    var call2 = TestEngine.registerCallback("watchPropertyCallback2", callbackFunction2, onError);
+    var call3 = TestEngine.registerCallback("watchPropertyCallback3", callbackFunction3, onError);
+
+    watcherId1 = DevStatusObj.watchPropertyChange(
+        call1.successCallback,
+        call1.errorCallback,
+        {
+            property:"batteryLevel",
+            aspect:"Battery"
+        },
+
+        {
+            maxNotificationInterval:2000 //every 2 second;
+        }
+        );
+
+    watcherId2 = DevStatusObj.watchPropertyChange(
+        call2.successCallback,
+        call2.errorCallback,
+        {
+            property:"availableSize",
+            aspect:"MemoryUnit"
+        },
+
+        {
+            maxNotificationInterval:1000 //every 1 second;
+        }
+        );
+
+    watcherId3 = DevStatusObj.watchPropertyChange(
+        call3.successCallback,
+        call3.errorCallback,
+        {
+            aspect:"Battery",
+            property:"batteryLevel"
+        },
+
+        {
+            maxNotificationInterval:2000 //every 2 second;
+        }
+        );
+}
+
+function watchClearPropertyChangeTest1() {
+    var watchId = 0;
+    var callbackFunction1 = function (value) {
+        TestEngine.test("Callback called: " + value, true);
+        DevStatusObj.clearPropertyChange(watchId);
+    }
+    var callObj = TestEngine.registerCallback("watchPropertyCallback", callbackFunction1, onError);
+
+    watchId = DevStatusObj.watchPropertyChange(
+        callObj.successCallback,
+        callObj.errorCallback,
+        {
+            property:"version",
+            aspect:"WebRuntime"
+        },
+
+        {
+            maxNotificationInterval:2000 //every 2 second;
+        }
+        );
+}
+
+function watchClearPropertyChangeTest2() {
+    var watchId = 0;
+    var callbackFunction1 = function (value) {
+        TestEngine.test("Callback called: " + value, true);
+        DevStatusObj.clearPropertyChange(watchId);
+    }
+    var callObj = TestEngine.registerCallback("watchPropertyCallback", callbackFunction1, onError);
+
+    watchId = DevStatusObj.watchPropertyChange(
+        callObj.successCallback,
+        callObj.errorCallback,
+        {
+            property:"version",
+            aspect:"WebRuntime"
+        },
+
+        {
+            minNotificationInterval:2000 //every 2 second;
+        }
+        );
+}
+
+function watchClearPropertyChangeTest3() {
+    var watchId = 0;
+    var callbackFunction1 = function (value) {
+        TestEngine.test("Callback called: " + value, true);
+        DevStatusObj.clearPropertyChange(watchId);
+    }
+    var callObj = TestEngine.registerCallback("watchPropertyCallback", callbackFunction1, onError);
+
+    watchId = DevStatusObj.watchPropertyChange(
+        callObj.successCallback,
+        callObj.errorCallback,
+        {
+            property:"version",
+            aspect:"WebRuntime"
+        }
+        );
+}
+
+function watchClearPropertyChangeTest4() {
+    var callbackCnt1 = 0;
+
+    var callbackFunction1 = function (value) {
+        jsPrint("callbackFunction1, value = " + value);
+        if (callbackCnt1 == 0) {
+            TestEngine.test("Callback called once", true);
+        } else {
+            TestEngine.test("Callback called more", false);
+        }
+        callbackCnt1++;
+    }
+
+    var callObj = TestEngine.registerCallback("callback counter check",
+        callbackFunction1, onError);
+
+    var watcherId1 = DevStatusObj.watchPropertyChange(
+        callObj.successCallback,
+        callObj.errorCallback,
+        {
+            property:"batteryLevel",
+            aspect:"Battery"
+        },
+
+        {
+            minChangePercent:50
+        }
+        );
+
+    var finalCallback = TestEngine.registerCallback("callback counter check",
+        function() {
+            jsPrint("TimeOut executed, trying to clear watch, id=" + watcherId1);
+
+            DevStatusObj.clearPropertyChange(watcherId1);
+
+            TestEngine.test("there should be invoked callback", callbackCnt1 == 1);
+        }
+        );
+
+    setTimeout(finalCallback.successCallback,
+        2500); //wait before continuing;
+}
+
+function cleaning() {
+    DevStatusObj = null;
+    aspectsProperty = null;
+    wrongProperty = null;
+    aspectsComponent = null;
+    TestEngine.test("null==DevStatusObj", null==DevStatusObj);
+    TestEngine.test("null==aspectsProperty", null==aspectsProperty);
+    TestEngine.test("null==wrongProperty", null==wrongProperty);
+    TestEngine.test("null==aspectsComponent", null==aspectsComponent);
+}
+
+//=============================================================================;
+
+TestEngine.setTestSuiteName("[WAC2.0][Devicestatus]", 10*1000); //5sec time out for callbacks;
+//TestEngine.addTest(true, presenceTest, "[WAC2.0][Devicestatus] Devicestatus functions presence test");
+TestEngine.addTest(true, getPropertyValueTestCellid, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTestCellid");
+//
+//TestEngine.addTest(true, getPropertyValueInvalidArgumentsTest, "[WAC2.0][Devicestatus] Devicestatus invalid argument test (getPropertyValue)");
+//TestEngine.addTest(true, watchPropertyChangeInvalidParametersTest, "[WAC2.0][Devicestatus] Devicestatus invalid argument test (watchPropertyChange)");
+//TestEngine.addTest(true, clearPropertyChangeInvalidParametersTest, "[WAC2.0][Devicestatus] Devicestatus invalid argument test (clearPropertyChange)");
+//TestEngine.addTest(true, getCompomentInvalidParametersTest, "[WAC2.0][Devicestatus] Devicestatus invalid argument test (getCompoment)");
+//TestEngine.addTest(true, isSupportedInvalidParametersTest, "[WAC2.0][Devicestatus] Devicestatus invalid argument test (isSupported)");
+//
+//TestEngine.addTest(true, getComponentsTest, "[WAC2.0][Devicestatus] Devicestatus getComponents");
+//
+//TestEngine.addTest(true, isSupportedTest, "[WAC2.0][Devicestatus] Devicestatus isSupported");
+//
+//TestEngine.addTest(true, getPropertyValueTest1a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest1a");
+//TestEngine.addTest(true, getPropertyValueTest1b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest1b");
+//TestEngine.addTest(true, getPropertyValueTest2a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest2a");
+//TestEngine.addTest(true, getPropertyValueTest3a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest3a");
+//TestEngine.addTest(true, getPropertyValueTest3b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest3b");
+//TestEngine.addTest(true, getPropertyValueTest3c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest3c");
+//TestEngine.addTest(true, getPropertyValueTest4a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest4a");
+//TestEngine.addTest(true, getPropertyValueTest4b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest4b");
+//TestEngine.addTest(true, getPropertyValueTest4c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest4c");
+//TestEngine.addTest(true, getPropertyValueTest4d, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest4d");
+//TestEngine.addTest(true, getPropertyValueTest5a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5a");
+//TestEngine.addTest(true, getPropertyValueTest5b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5b");
+//TestEngine.addTest(true, getPropertyValueTest5c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5c");
+//TestEngine.addTest(true, getPropertyValueTest5d, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5d");
+//TestEngine.addTest(true, getPropertyValueTest5e, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5e");
+//TestEngine.addTest(true, getPropertyValueTest5f, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest5f");
+//TestEngine.addTest(true, getPropertyValueTest6a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest6a");
+//TestEngine.addTest(true, getPropertyValueTest6b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest6b");
+//TestEngine.addTest(true, getPropertyValueTest6c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest6c");
+//TestEngine.addTest(true, getPropertyValueTest7a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest7a");
+//TestEngine.addTest(true, getPropertyValueTest7b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest7b");
+//TestEngine.addTest(true, getPropertyValueTest7c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest7c");
+//TestEngine.addTest(true, getPropertyValueTest7d, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest7d");
+//TestEngine.addTest(true, getPropertyValueTest8a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest8a");
+//TestEngine.addTest(true, getPropertyValueTest8b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest8b");
+//TestEngine.addTest(true, getPropertyValueTest8c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest8c");
+//TestEngine.addTest(true, getPropertyValueTest8d, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest8d");
+//TestEngine.addTest(true, getPropertyValueTest8e, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest8e");
+//TestEngine.addTest(true, getPropertyValueTest9a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest9a");
+//TestEngine.addTest(true, getPropertyValueTest10a, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest10a");
+//TestEngine.addTest(true, getPropertyValueTest10b, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest10b");
+//TestEngine.addTest(true, getPropertyValueTest10c, "[WAC2.0][Devicestatus] Devicestatus getPropertyValueTest10c");
+//
+//TestEngine.addTest(true, watchClearPropertyChangeTest, "[WAC2.0][Devicestatus] Devicestatus watchClearPropertyChangeTest");
+//TestEngine.addTest(true, watchClearPropertyChangeTest1, "[WAC2.0][Devicestatus] Devicestatus watchClearPropertyChangeTest1");
+//TestEngine.addTest(true, watchClearPropertyChangeTest2, "[WAC2.0][Devicestatus] Devicestatus watchClearPropertyChangeTest2");
+//TestEngine.addTest(true, watchClearPropertyChangeTest3, "[WAC2.0][Devicestatus] Devicestatus watchClearPropertyChangeTest3");
+//TestEngine.addTest(true, watchClearPropertyChangeTest4, "[WAC2.0][Devicestatus] Devicestatus watchClearPropertyChangeTest4");
+
+TestEngine.addTest(true, cleaning, "[WAC2.0][Devicestatus] Cleaning data");
+
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestFilesystem.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestFilesystem.js
new file mode 100644 (file)
index 0000000..980cd74
--- /dev/null
@@ -0,0 +1,3440 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+// -------------------------| Globals
+var MAX_PATH_LENGTH = 256;
+
+var LOCATION_SPECIFIERS = new Array(
+    'wgt-package',
+    'wgt-private',
+    'wgt-private-tmp',
+    'documents',
+    'images',
+    'videos',
+    'removable',
+    'downloads'
+);
+
+var TEST_ROOT_LOCATION = 'downloads';
+
+// -------------------------| Error verification prerequisites
+TestEngine.setErrorType(Object);
+TestEngine.setErrorField('code');
+var TYPE_MISMATCH_ERR = 17;
+var IO_ERR = 100;
+var INVALID_VALUES_ERR = 22;
+var SECURITY_ERR = 18;
+var NOT_FOUND_ERR = 8;
+var UNKNOWN_ERR = 0;
+
+// -------------------------| Setting up environment.
+try {
+  function on_resolve_error(err) { }
+  function on_resolve_success(file) {
+    function on_listFiles_success(files) {
+      for (i = 0; i < files.length; ++i) {
+        if (files[i].name.match(/^test_wac20_filesystem_/)) {
+          files[i].isDirectory ? deleteDirectory(file, files[i]) : deleteFile(file, files[i]);
+        }
+      }
+    }
+    function on_listFiles_error(err) {
+      TestEngine.log("Error while listing files.");
+    }
+    file.listFiles(on_listFiles_success, on_listFiles_error);
+  }
+  deviceapis.filesystem.resolve(on_resolve_success, on_resolve_error, TEST_ROOT_LOCATION);
+}
+catch (e) {
+  TestEngine.log("Exception while setting up environment.");
+}
+
+// -------------------------| Tests
+// WAC2-FILESYSTEM-001: Check filesystem manager properties.
+function test_filesystem_properties_001() {
+  var props = new Array();
+  props.push(new Array('maxPathLength', MAX_PATH_LENGTH, 0, true, TestEngine.NUMBER));
+  TestEngine.testProperties(deviceapis.filesystem, props);
+}
+
+// WAC2-FILESYSTEM-002: Resolve a file.
+function test_filesystem_resolve_002() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) { TestEngine.test("resolve()", isFileObject(file));}
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-003: Resolve a non-existent file.
+function test_filesystem_resolve_003() {
+  function on_resolve_error(err) {
+    TestEngine.test("resolve() non-existent file [IO_ERR]", (err.code == IO_ERR));
+  }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve() non-existent file [IO_ERR]", false);
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, "locationdd");
+}
+
+// WAC-FILESYSTEM-004: List files from root directory.
+function test_file_listFiles_004() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles() [" + err.code + "]", false);
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", isArray(files));
+    }
+    var cb = TestEngine.registerCallback("listFiles", on_listFiles_success, on_listFiles_error);
+    file.listFiles(cb.successCallback, cb.errorCallback);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-005: Open file in read mode.
+function test_file_open_005() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      deleteFile(file, file2);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    var stream = file2.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-006: Open file in write mode.
+function test_file_open_006() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file2 = file.createFile(getFileName());
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      deleteFile(file, file2);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    var stream = file2.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-007: Open file in append mode.
+function test_file_open_007() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      deleteFile(file, file2);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    var stream = file2.openStream(cb.successCallback, cb.errorCallback, "a", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-008: Call open function with invalid value of parameter 'mode'.
+function test_file_open_error_008() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    function on_openStream_error(err) {
+      TestEngine.test("Calling openStream() with invalid mode.", err.code === err.INVALID_VALUES_ERR);
+      deleteFile(file, file2);
+    }
+    function on_openStream_success(fs) {
+      TestEngine.test("Calling openStream() with invalid mode.", false);
+      fs.close();
+      deleteFile(file, file2);
+    }
+    var file2 = file.createFile(getFileName());
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file2.openStream(cb.successCallback, cb.errorCallback, "x", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-009: Call open function with invalid value of parameter 'encoding'.
+function test_file_open_error_009() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    function on_openStream_error(err) {
+      TestEngine.test("Calling openStream() with invalid encoding.", err.code === err.INVALID_VALUES_ERR);
+      deleteFile(file, file2);
+    }
+    function on_openStream_success(fs) {
+      TestEngine.test("Calling openStream() with invalid encoding.", false);
+      fs.close();
+      deleteFile(file, file2);
+    }
+    var file2 = file.createFile(getFileName());
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file2.openStream(cb.successCallback, cb.errorCallback, "r", "cp-1250");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-010: Copy file w/o overwrite.
+function test_file_copyTo_010() {
+  var g_file = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteFile(file, g_file);
+    }
+    function on_copyTo_success(file2) {
+      TestEngine.test("copyTo()", isFile(file2));
+      deleteFile(file, file2);
+      deleteFile(file, g_file);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    file.copyTo(cb.successCallback, cb.errorCallback, g_file.fullPath, file.fullPath + "/" + getFileName(), false);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-011: Copy file w/o overwrite when destination exists.
+function test_file_copyTo_error_011() {
+  var g_file = null;
+  var g_dest = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_dest = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_dest));
+
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteFile(file, g_file);
+      deleteFile(file, g_dest);
+    }
+    function on_copyTo_success(file2) {
+      TestEngine.test("copyTo()", false);
+      deleteFile(file, file2);
+      deleteFile(file, g_file);
+      deleteFile(file, g_dest);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    file.copyTo(cb.successCallback, cb.errorCallback, g_file.fullPath, file.fullPath + "/" + g_dest.name, false);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-012: Copy file with overwrite when destination exists.
+function test_file_copyTo_012() {
+  var g_file = null;
+  var g_dest = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_dest = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_dest));
+
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteFile(file, g_file);
+      deleteFile(file, g_dest);
+    }
+    function on_copyTo_success(file2) {
+      TestEngine.test("copyTo()", isFile(file2));
+      deleteFile(file, file2);
+      deleteFile(file, g_file);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    file.copyTo(cb.successCallback, cb.errorCallback, g_file.fullPath, file.fullPath + "/" + g_dest.name, true);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-013: Create file.
+function test_file_createFile_013() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file1 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file1));
+    deleteFile(file, file1);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-014: Create file with invalid characters in path.
+function test_file_createFile_error_014() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.log("Calling createFile() with invalid characters in path. [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file, "createFile", "!@#$%^&*(");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-015: Create file when it already exists.
+function test_file_createFile_error_015() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file1 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file1));
+    TestEngine.log("Calling createFile() with path that already exists. [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file, "createFile", file1.name);
+    deleteFile(file, file1);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-016: Create file in file instead of directory.
+function test_file_createFile_error_016() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file1 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file1));
+    TestEngine.log("Calling createFile() on file object. [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file1, "createFile", getFileName());
+    deleteFile(file, file1);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-017: Create file with invalid path componenet - "..".
+function test_file_createFile_error_017() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.testPresetError(
+        "Calling createFile() with invalid path component - \"..\".",
+        function(){file.createFile("../testFile_021");},
+        INVALID_VALUES_ERR
+    );
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-018: Create directory.
+function test_file_createDirectory_018() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+    deleteDirectory(file, dir);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-019: Create directory with invalid character in path.
+function test_file_createDirectory_error_019() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.log("Calling createDirectory() with invalid character in path. - [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file, "createDirectory", "!@#$%^&*(");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-020: Create directory when it already exists.
+function test_file_createDirectory_error_020() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+    TestEngine.log("Calling createDirectory() with path that already exists. - [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file, "createDirectory", dir.name);
+    deleteDirectory(file, dir);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-021: Create directory in file instead of directory.
+function test_file_createDirectory_error_021() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file1 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file1));
+    TestEngine.log("Calling createDirectory() on file object. - [NULL OBJECT]");
+    TestEngine.catchErrorType("code", 100, file1, "createDirectory", getDirName());
+    deleteFile(file, file1);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-022: Create file with invalid path componenet - "..".
+function test_file_createDirectory_error_022() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.testPresetError(
+      "Calling createDirectory() with invalid path component - \"..\".",
+      function(){file.createDirectory("../" + getDirName());},
+      INVALID_VALUES_ERR
+    );
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-023: Move file w/o overwrite.
+function test_file_moveTo_023() {
+  var g_file = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", false);
+      deleteFile(file, g_file);
+    }
+    function on_moveTo_success(file1) {
+      TestEngine.test("moveTo()", true);
+      deleteFile(file, file1);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    file.moveTo(cb.successCallback, cb.errorCallback, g_file.fullPath, file.fullPath + "/" + getFileName(), false);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-024: Move file w/o overwrite when destination exists.
+function test_file_moveTo_error_024() {
+  var g_file = null;
+  var g_dest = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_dest = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_dest));
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [IO_ERR]", (err.code == IO_ERR));
+      deleteFile(file, g_file);
+      deleteFile(file, g_dest);
+    }
+    function on_moveTo_success(file1) {
+      TestEngine.test("moveTo()", false);
+      deleteFile(file, file1);
+      deleteFile(file, g_dest);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    file.moveTo(cb.successCallback, cb.errorCallback, g_file.fullPath, g_dest.fullPath, false);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-025: Move file with overwrite when destination exists.
+function test_file_moveTo_025() {
+  var g_file = null;
+  var g_dest = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_dest = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_dest));
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", false);
+      deleteFile(file, g_file);
+      deleteFile(file, g_dest);
+    }
+    function on_moveTo_success(file1) {
+      TestEngine.test("moveTo()", isFile(file1));
+      deleteFile(file, file1);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    file.moveTo(cb.successCallback, cb.errorCallback, g_file.fullPath, g_dest.fullPath, true);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-026: Delete a file.
+function test_file_deleteFile_026() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    deleteFile(file, f);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-027: Call deleteFile() on a directory.
+function test_file_deleteFile_error_027() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+    function on_deleteFile_error(err) {
+      TestEngine.test("deleteFile() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+      deleteDirectory(file, dir);
+    }
+    function on_deleteFile_success() {
+      TestEngine.test("deleteFile()", false);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+    file.deleteFile(cb.successCallback, cb.errorCallback, dir.fullPath);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-028: Call deleteFile() on a file.
+function test_file_deleteFile_error_028() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file1 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file1));
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    function on_deleteFile_error(err) {
+      TestEngine.test("Call deleteFile() on a file. [IO_ERR]", (err.code == IO_ERR));
+      deleteFile(file, file1);
+      deleteFile(file, file2);
+    }
+    function on_deleteFile_success() {
+      TestEngine.test("Call deleteFile() on a file. [IO_ERR]", false);
+      deleteFile(file, file2);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+    file1.deleteFile(cb.successCallback, cb.errorCallback, file2.fullPath);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-029: Call deleteFile() on the same file twice.
+function test_file_deleteFile_error_029() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    deleteFile(file, f);
+    function on_deleteFile_error(err) {
+      TestEngine.test("Call deleteFile() on a file that has already been deleted. [IO_ERR]", (err.code == IO_ERR));
+    }
+    function on_deleteFile_success() {
+      TestEngine.test("Call deleteFile() on a file that has already been deleted. [IO_ERR]", false);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+    file.deleteFile(cb.successCallback, cb.errorCallback, f.fullPath);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-030: Call deleteFile() on opened file.
+function test_file_deleteFile_error_030() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      function on_deleteFile_error(err) {
+        TestEngine.test("Call deleteFile() on opened file. [IO_ERR]", (err.code == IO_ERR));
+        stream.close();
+        deleteFile(file, f);
+      }
+      function on_deleteFile_success() {
+        TestEngine.test("Call deleteFile() on opened file. [IO_ERR]", false);
+        stream.close();
+      }
+      var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+      file.deleteFile(cb.successCallback, cb.errorCallback, f.fullPath);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-031: Delete a directory.
+function test_file_deleteDirectory_031() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+    deleteDirectory(file, dir);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-032: Call deleteDirectory() on a file.
+function test_file_deleteDirectory_error_032() {
+  var g_file = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_file = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(g_file));
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("Call deleteDirectory() on a file. [IO_ERR] [" + err.code + "]", (err.code == IO_ERR));
+      deleteFile(file, g_file);
+    }
+    function on_deleteDirectory_success(file) {
+      TestEngine.test("deleteDirectory()", false);
+      deleteFile(file, g_file);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+    g_file.deleteDirectory(cb.successCallback, cb.errorCallback, "foo", true);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-033: Call deleteDirectory() on the same directory twice.
+function test_file_deleteDirectory_error_033() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+      function on_deleteDirectory2_error(err) {
+        TestEngine.test("Call deleteDirectory() on a dir that has already been deleted. [IO_ERR] [" + err.code + "]", (err.code == IO_ERR));
+      }
+      function on_deleteDirectory2_success(file) {
+        TestEngine.test("deleteDirectory()", false);
+      }
+    deleteDirectory(file, dir);
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory2_success, on_deleteDirectory2_error);
+    file.deleteDirectory(cb.successCallback, cb.errorCallback, dir.fullPath, true);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-034: Call deleteDirectory() non-recursively on non-empty directory.
+function test_file_deleteDirectory_error_034() {
+  var g_dir = null;
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    g_dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(g_dir));
+    TestEngine.test("createFile()", isFile(g_dir.createFile(getFileName())));
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("Call deleteDirectory() non-recursively on non-empty dir. [IO_ERR]", (err.code == IO_ERR));
+      deleteDirectory(file, g_dir);
+    }
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", false);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+    file.deleteDirectory(cb.successCallback, cb.errorCallback, g_dir.fullPath, false);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-035: Call write()/read() on a stream.
+function test_filestream_write_read_035() {
+  var test_string = "It's alive! Alive!";
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream1) {
+      TestEngine.test("openStream()", isFilestream(stream1));
+      stream1.write(test_string);
+      stream1.close();
+      function on_openStream1_success(r_stream) {
+        TestEngine.test("openStream()", isFilestream(r_stream));
+        var read_string = r_stream.read(test_string.length);
+        r_stream.close();
+        TestEngine.test("write()/read()", (read_string === test_string));
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-036: Call read() on a closed stream.
+function test_filestream_read_error_036() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    try {
+        var f = file.createFile(getFileName());
+        TestEngine.test("createFile success - should fail", false);
+    } catch (e) {
+        TestEngine.test("createFile failed.", true);
+    }
+//    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call read() on a closed stream. [IO_ERR]",
+        function(){stream.read(3);},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", true);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-037: Call read() on a stream with EOF flag set.
+function test_filestream_read_error_037() {
+  var test_string = "It's alive! Alive!";
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_string);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_string = stream1.read(test_string.length);
+        TestEngine.testPresetError(
+          "Call read() on stream with EOF set. [IO_ERR]",
+          function(){stream1.read(1);},
+          IO_ERR
+        );
+        stream1.close();
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-038: Call openStream() on a directory.
+function test_file_open_error_038() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+    function on_openStream_success(stream) {
+      TestEngine.test("Call openStream() on a directory.", false);
+      stream.close();
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("Call openStream() on a directory. [IO_ERR]", (err.code == IO_ERR));
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    dir.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    deleteDirectory(file, dir);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-040: Call read() on write-only stream.
+function test_filestream_read_error_040() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call read() on write-only stream. [IO_ERR]",
+        function(){stream.read(0);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-041: Call write() on a closed stream.
+function test_filestream_write_error_041() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call write() on a closed stream. [IO_ERR]",
+        function(){stream.write('test');},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-042: Call write() on read-only stream.
+function test_filestream_write_error_042() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call write() on read-only stream. [IO_ERR]",
+        function(){stream.write('test');},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-043
+// Parameters: stringData = array
+// Result: Test passes (toString() called on JS Array).
+function test_filestream_write_error_043() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(new Array('t','e','s','t'));
+      TestEngine.test("write()", true);
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-044: Call write() w/o argument.
+function test_filestream_write_error_044() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call write() w/o argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.write();},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-045: Call read() with invalid argument type.
+function test_filestream_read_error_045() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.test("read()", stream.read('should be a number') == '');
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-046: Call read() w/o argument.
+function test_filestream_read_error_046() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call read() w/o argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.read();},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-047: Call writeBytes()/readBytes() on a stream.
+function test_filestream_writeBytes_readBytes_047() {
+  var test_array = new Array(1, 2, 3, 4);
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBytes(test_array);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_array = stream1.readBytes(test_array.length);
+        stream1.close();
+        var cmp = false;
+        if (test_array.length == read_array.length) {
+          cmp = true;
+          for (i = 0; i < test_array.length; ++i) {
+            if (test_array[i] != read_array[i]) {
+              cmp = false;
+              break;
+            }
+          }
+        }
+        TestEngine.test("writeBytes()/readBytes()", cmp);
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-048: Call readBytes() on a closed stream.
+function test_filestream_readBytes_error_048() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call readBytes() on a closed stream. [IO_ERR]",
+        function(){stream.readBytes(3);},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-049: Call readBytes() on a stream with EOF flag set.
+function test_filestream_readBytes_error_049() {
+  var test_array = new Array(1, 2, 3, 4);
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBytes(test_array);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_array = stream1.readBytes(100);
+        TestEngine.testPresetError(
+          "Call readBytes() on stream with EOF set. [IO_ERR]",
+          function(){stream1.readBytes(1);},
+          IO_ERR
+        );
+        stream1.close();
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-051: Call readBytes() on write-only stream.
+function test_filestream_readBytes_error_051() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call readBytes() on write-only stream. [IO_ERR]",
+        function(){stream.readBytes(0);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-052
+// Parameters: byteCount = string
+// Result: Test passes (conversion exception).
+function test_filestream_readBytes_error_052() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.test("readBytes()", stream.readBytes('should be a number').length == 0);
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-053: Call readBytes() w/o argument.
+function test_filestream_readBytes_error_053() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call read() w/o argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.readBytes();},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-054: Call writeBytes() on a closed stream.
+function test_filestream_writeBytes_error_054() {
+  var test_array = new Array(1, 2, 3, 4);
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call writeBytes() on a closed stream. [IO_ERR]",
+        function(){stream.writeBytes(test_array);},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-055: Call writeBytes() on read-only stream.
+function test_filestream_writeBytes_error_055() {
+  var test_array = new Array(1, 2, 3, 4);
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call writeBytes() on read-only stream. [IO_ERR]",
+        function(){stream.writeBytes(test_array);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-056: Call writeBytes() with invalid argument type.
+function test_filestream_writeBytes_error_056() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call writeBytes() with invalid argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.writeBytes(3);},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-057: Call writeBytes() w/o argument.
+function test_filestream_writeBytes_057() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBytes();
+      stream.close();
+
+      function on_openStream_read_success(stream) {
+        TestEngine.test("openStream()", isFilestream(stream));
+        var readData = stream.readBytes(256);
+        stream.close();
+        TestEngine.test("readBytes()", isArray(readData) && readData.length == 0);
+        deleteFile(file, f);
+      }
+
+      var cb = TestEngine.registerCallback("openStream", on_openStream_read_success, on_openStream_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-058: Call writeBase64()/readBase64() on a stream.
+function test_filestream_writeBase64_readBase64_058() {
+  var test_base64 = 'dGVzdA==';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBase64(test_base64);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_base64 = stream1.readBase64(100);
+        stream1.close();
+        TestEngine.test("writeBase64()/readBase64()", (test_base64 === read_base64));
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-059: Call writeBase64()/read() on a stream.
+function test_filestream_writeBase64_read_059() {
+  var test_base64 = 'dGVzdA==';
+  var test_string = 'test';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBase64(test_base64);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_string = stream1.read(test_string.length);
+        stream1.close();
+        TestEngine.test("writeBase64()/read()", (test_string === read_string));
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-060: Call write()/readBase64() on a stream.
+function test_filestream_write_readBase64_060() {
+  var test_base64 = 'dGVzdA==';
+  var test_string = 'test';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_string);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_base64 = stream1.readBase64(100);
+        stream1.close();
+        TestEngine.test("write()/readBase64()", (test_base64 === read_base64));
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-061: Call readBase64() on a closed stream.
+function test_filestream_readBase64_error_061() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call readBase64() on a closed stream. [IO_ERR]",
+        function(){stream.readBase64(3);},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-062: Call readBase64() on a stream with EOF flag set.
+function test_filestream_readBase64_error_062() {
+  var test_base64 = 'dGVzdA==';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBase64(test_base64);
+      stream.close();
+      function on_openStream1_success(stream1) {
+        TestEngine.test("openStream()", isFilestream(stream1));
+        var read_base64 = stream1.readBase64(100);
+        TestEngine.testPresetError(
+          "Call readBase64() on stream with EOF set. [IO_ERR]",
+          function(){stream1.readBase64(1);},
+          IO_ERR
+        );
+        stream1.close();
+        deleteFile(file, f);
+      }
+      function on_openStream1_error(err) {
+        TestEngine.test("openStream() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream1_success, on_openStream1_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-064: Call readBase64() on write-only stream.
+function test_filestream_readBase64_error_064() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call readBase64() on write-only stream. [IO_ERR]",
+        function(){stream.readBase64(0);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-065
+// Parameters: byteCount = string
+// Result: Test passes (empty string).
+function test_filestream_readBase64_error_065() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.test("readBase64()", stream.readBase64('should be a number') == '');
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-066: Call readBase64() w/o argument.
+function test_filestream_readBase64_error_066() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call readBase64() w/o argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.readBase64();},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-067: Call writeBase64() on a closed stream.
+function test_filestream_writeBase64_error_067() {
+  var test_base64 = 'dGVzdA==';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      TestEngine.testPresetError(
+        "Call writeBase64() on a closed stream. [IO_ERR]",
+        function(){stream.writeBase64(test_base64);},
+        IO_ERR
+      );
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-068: Call writeBase64() on read-only stream.
+function test_filestream_writeBase64_error_068() {
+  var test_base64 = 'dGVzdA==';
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call writeBase64() on read-only stream. [IO_ERR]",
+        function(){stream.writeBase64(test_base64);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-069
+// Parameters: base64Data = invalid value
+// Result: IO_ERR thrown in place.
+function test_filestream_writeBase64_error_069() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call writeBase64() with invalid argument.",
+        function(){stream.writeBase64(3);},
+        IO_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-070: Call writeBase64() w/o argument.
+function test_filestream_writeBase64_error_070() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.testPresetError(
+        "Call writeBase64() w/o argument. [TYPE_MISMATCH_ERR]",
+        function(){stream.writeBase64();},
+        TYPE_MISMATCH_ERR
+      );
+      stream.close();
+      deleteFile(file, f);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-071: Call createFile() on node resolved in read-only mode.
+function test_file_createFile_error_071() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.testPresetError(
+      "Call createFile() on read-only node. [SECURITY_ERR]",
+      function() {
+        var f = file.createFile(getFileName());
+        deleteFile(file, f);
+      },
+      SECURITY_ERR
+    );
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "r");
+}
+
+// WAC-FILESYSTEM-072: Call deleteFile() on node resolved in read-only mode.
+function test_file_deleteFile_error_072() {
+  var filename = getFileName();
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("createFile()", isFile(file.createFile(filename)));
+
+    function on_resolve1_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+    function on_resolve1_success(file) {
+      var f = file.resolve(filename);
+      TestEngine.test("resolve()", isFile(f));
+
+      function on_deleteFile_error(err) {
+        TestEngine.test("Call deleteFile() on read-only node. [SECURITY_ERR]", (err.code == SECURITY_ERR));
+        function on_resolve2_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+        function on_resolve2_success(file) {
+          var f = file.resolve(filename);
+          TestEngine.test("resolve()", isFile(f));
+          deleteFile(file, f);
+        }
+        var cb = TestEngine.registerCallback("resolve", on_resolve2_success, on_resolve2_error);
+        deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+      }
+      function on_deleteFile_success() {
+        TestEngine.test("Call deleteFile() on read-only node. [SECURITY_ERR]", false);
+      }
+      var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+      file.deleteFile(cb.successCallback, cb.errorCallback, f.fullPath);
+    }
+    var cb = TestEngine.registerCallback("resolve", on_resolve1_success, on_resolve1_error);
+    deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "r");
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+}
+
+// WAC-FILESYSTEM-073: Call deleteDirectory() on node resolved in read-only mode.
+function test_file_deleteDirectory_error_073() {
+  var dirname = getDirName();
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("createDirectory()", isDir(file.createDirectory(dirname)));
+
+    function on_resolve1_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+    function on_resolve1_success(file) {
+      var dir = file.resolve(dirname);
+      TestEngine.test("resolve()", isDir(dir));
+
+      function on_deleteDirectory_error(err) {
+        TestEngine.test("Call deleteDirectory() on read-only node. [SECURITY_ERR]", (err.code == SECURITY_ERR));
+        function on_resolve2_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+        function on_resolve2_success(file) {
+          var dir = file.resolve(dirname);
+          TestEngine.test("resolve()", isDir(dir));
+          deleteDirectory(file, dir);
+        }
+        var cb = TestEngine.registerCallback("resolve", on_resolve2_success, on_resolve2_error);
+        deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+      }
+      function on_deleteDirectory_success() {
+        TestEngine.test("Call deleteDirectory() on read-only node. [SECURITY_ERR]", false);
+      }
+      var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+      file.deleteDirectory(cb.successCallback, cb.errorCallback, dir.fullPath, true);
+    }
+    var cb = TestEngine.registerCallback("resolve", on_resolve1_success, on_resolve1_error);
+    deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "r");
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+}
+
+// WAC-FILESYSTEM-074: Call moveTo() on node resolved in read-only mode.
+function test_file_moveTo_error_074() {
+  var src_filename = getFileName();
+  var dst_filename = getFileName();
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(src_filename);
+    TestEngine.test("createFile()", isFile(f));
+
+    function on_resolve1_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+    function on_resolve1_success(file) {
+      var f = file.resolve(src_filename);
+      TestEngine.test("resolve()", isFile(f));
+
+      function on_moveTo_error(err) {
+        TestEngine.test("Call moveTo() on read-only mode. [SECURITY_ERR]", (err.code == SECURITY_ERR));
+        function on_resolve2_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+        function on_resolve2_success(file) {
+          var f = file.resolve(src_filename);
+          TestEngine.test("resolve()", isFile(f));
+          deleteFile(file, f);
+        }
+        var cb = TestEngine.registerCallback("resolve", on_resolve2_success, on_resolve2_error);
+        deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+      }
+      function on_moveTo_success(file1) {
+        TestEngine.test("Call moveTo() on read-only mode. [SECURITY_ERR]", false);
+        function on_resolve2_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+        function on_resolve2_success(file) {
+          var f = file.resolve(dst_filename);
+          TestEngine.test("resolve()", isFile(f));
+          deleteFile(file, f);
+        }
+        var cb = TestEngine.registerCallback("resolve", on_resolve2_success, on_resolve2_error);
+        deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+      }
+      var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+      file.moveTo(cb.successCallback, cb.errorCallback, f.fullPath, file.fullPath + '/' + dst_filename, true);
+    }
+    var cb = TestEngine.registerCallback("resolve", on_resolve1_success, on_resolve1_error);
+    deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "r");
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+}
+
+// WAC-FILESYSTEM-075: Call openStream() in write-only mode on node resolved in read-only mode.
+function test_file_openStream_error_075() {
+  var filename = getFileName();
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(filename);
+    TestEngine.test("createFile()", isFile(f));
+
+    function on_resolve1_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+    function on_resolve1_success(r_file) {
+      var f = r_file.resolve(filename);
+      TestEngine.test("resolve()", isFile(f));
+
+      function on_openStream_success(stream) {
+        TestEngine.test("Call openStream() in write-only mode on read-only node. [SECURITY_ERR]", false);
+        stream.close();
+        deleteFile(file, f);
+      }
+      function on_openStream_error(err) {
+        TestEngine.test("Call openStream() in write-only mode on read-only node. [SECURITY_ERR]", (err.code == SECURITY_ERR));
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+      f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+    }
+    var cb = TestEngine.registerCallback("resolve", on_resolve1_success, on_resolve1_error);
+    deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "r");
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, "rw");
+}
+
+// WAC-FILESYSTEM-076: Call readAsText() on a file.
+function test_file_readAsText_076() {
+  var test_content = "Ala ma kota";
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", false);
+        deleteFile(file, f);
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(file, f);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      f.readAsText(cb.successCallback, cb.errorCallback, "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(file, f);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    f.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-077: Call readAsText() on a directory.
+function test_file_readAsText_error_077() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var dir = file.createDirectory(getDirName());
+    TestEngine.test("createDirectory()", isDir(dir));
+
+    function on_readAsText_error(err) {
+      TestEngine.test("Call readAsText() on a directory [IO_ERR]", (err.code == IO_ERR));
+    }
+    function on_readAsText_success(str) {
+      TestEngine.test("Call readAsText() on a directory [IO_ERR]", false);
+    }
+    var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+    dir.readAsText(cb.successCallback, cb.errorCallback, "UTF-8");
+    deleteDirectory(file, dir);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-078: Call readAsText() on a deleted file.
+function test_file_readAsText_error_078() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(root) {
+    var file = root.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file));
+
+    function on_deleteFile_error(err) { TestEngine.test("deleteFile() [" + err.code + "]", false); }
+    function on_deleteFile_success() {
+      function on_readAsText_error(err) {
+        TestEngine.test("Call readAsText() on a deleted file [IO_ERR]", (err.code == IO_ERR));
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("Call readAsText() on a deleted file [IO_ERR]", false);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback, "UTF-8");
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+    root.deleteFile(cb.successCallback, cb.errorCallback, file.fullPath);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-079: Call toUri() on file located in root folder.
+function test_file_toUri_079() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var f = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(f));
+    var uri = f.toURI();
+    TestEngine.test("Call toUri() returns non empty string", isString(uri) && uri.length > 0);
+    TestEngine.log("created uri: " + uri);
+    deleteFile(file, f);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-080: Resolve a file with mode set to null.
+function test_filesystem_resolve_080() {
+  function on_resolve_error(err) {
+    TestEngine.test("resolve()", false);
+  }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", true);
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, null);
+}
+
+// WAC-FILESYSTEM-081: List files with null passed as filter.
+function test_file_listFiles_081() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles() [" + err.code + "]", false);
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", isArray(files));
+    }
+    var cb = TestEngine.registerCallback("listFiles", on_listFiles_success, on_listFiles_error);
+    file.listFiles(cb.successCallback, cb.errorCallback, null);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-082: List files with undefined passed as filter.
+function test_file_listFiles_082() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles() [" + err.code + "]", false);
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", isArray(files));
+    }
+    var cb = TestEngine.registerCallback("listFiles", on_listFiles_success, on_listFiles_error);
+    file.listFiles(cb.successCallback, cb.errorCallback, undefined);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-083
+// Parameters: filter = 1, others = valid
+// Result: Test passes.
+function test_file_listFiles_error_083() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles()", false);
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", isArray(files));
+    }
+    var cb = TestEngine.registerCallback("listFiles", on_listFiles_success, on_listFiles_error);
+    file.listFiles(cb.successCallback, cb.errorCallback, 1);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-084: List files with null passed as success callback.
+function test_file_listFiles_error_084() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", false);
+    }
+    var cb = TestEngine.registerCallback("listFiles", on_listFiles_success, on_listFiles_error);
+    file.listFiles(null, cb.errorCallback);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-085
+// Parameters: successCallback = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_listFiles_error_085() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles()", (err.code == INVALID_VALUES_ERR));
+    }
+    var cb = TestEngine.registerCallback("listFiles", undefined, on_listFiles_error);
+    file.listFiles(cb.successCallback, cb.errorCallback);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-086: List files with both callbacks set to null. Nothing should happen.
+function test_file_listFiles_error_086() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    function on_listFiles_error(err) {
+      TestEngine.test("listFiles() [" + err.code + "]", false);
+    }
+    function on_listFiles_success(files) {
+      TestEngine.test("listFiles()", false);
+    }
+    // Pass callbacks directly to prevent "widget run timeout".
+    file.listFiles(null, null);
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-087: Test optionality of the last parameter.
+function test_file_open_087() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.close();
+      deleteFile(file, file2);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    var stream = file2.openStream(cb.successCallback, cb.errorCallback, "r");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-088: Test success callback set to null.
+function test_file_open_error_088() {
+  function on_resolve_success(root) {
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    var file = createFileForParent(root);
+    // Pass callbacks directly to prevent "widget run timeout".
+    var cb = TestEngine.registerCallback("openStream", null, on_openStream_error);
+    var stream = file.openStream(null, cb.errorCallback, "r");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-089
+// Parameters: successCallback = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_open_error_089() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    
+    var cb = TestEngine.registerCallback("openStream", undefined, on_openStream_error);
+    var stream = file.openStream(cb.successCallback, cb.errorCallback, "r");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-090: Test passing invalid mode with error callback set to null.
+function test_file_open_error_090() {
+  function on_resolve_success(root) {
+    function on_openStream_success(fs) {
+      TestEngine.test("Calling openStream() with invalid mode.", false);
+      fs.close();
+      deleteFile(root, file);
+    }
+    var file = createFileForParent(root);
+    testNoExceptionWithMessage("openStream()", function() {
+      // Pass callbacks directly to prevent "widget run timeout".
+      file.openStream(on_openStream_success, null, "x", "UTF-8");
+    });
+    deleteFile(root, file);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-091: Call readAsText() w/o specifing encoding parameter.
+function test_file_readAsText_091() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", false);
+        deleteFile(root, file);
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-092: Call readAsText() with encoding parameter set to null.
+function test_file_readAsText_092() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", false);
+        deleteFile(root, file);
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback, null);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-093: Call readAsText() with error callback set to null.
+function test_file_readAsText_093() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, null);
+      file.readAsText(cb.successCallback, null);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-094: Call readAsText() w/o specifing error callback.
+function test_file_readAsText_094() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, null);
+      file.readAsText(cb.successCallback);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-095: Call readAsText() with success callback set to null.
+function test_file_readAsText_error_095() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", null, on_readAsText_error);
+      file.readAsText(null, cb.errorCallback);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-096: Call readAsText() with both callbacks set to null.
+function test_file_readAsText_error_096() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      testNoExceptionWithMessage("readAsText()", function() {
+        file.readAsText(null, null);
+      });
+      deleteFile(root, file);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-097
+// Parameters: successCallback = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_readAsText_error_097() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText()", (err.code == INVALID_VALUES_ERR));
+        deleteFile(root, file);
+      }
+      
+      var cb = TestEngine.registerCallback("readAsText", undefined, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback, "r");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-098: Call readAsText() with invalid encoding parameter.
+function test_file_readAsText_error_098() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+        deleteFile(root, file);
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", false);
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback, "INVALID");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-099: Call deleteDirectory() with error callback set to null.
+function test_file_deleteDirectory_099() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", true);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, null);
+    root.deleteDirectory(cb.successCallback, null, dir.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-100: Call deleteDirectory() with error callback set to null
+//                     and directory set to invalid value.
+function test_file_deleteDirectory_error_100() {
+  function on_resolve_success(root) {
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", false);
+    }
+    testNoExceptionWithMessage("deleteDirectory()", function() {
+      // Pass callbacks directly to prevent "widget run timeout".
+      root.deleteDirectory(on_deleteDirectory_success, null, "../", true);
+    });
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-101: Call deleteDirectory() with success callback set to null.
+function test_file_deleteDirectory_error_101() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("deleteDirectory() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", null, on_deleteDirectory_error);
+    root.deleteDirectory(null, cb.errorCallback, dir.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-102
+// Parameters: successCallback = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_deleteDirectory_error_102() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("deleteDirectory()", (err.code == INVALID_VALUES_ERR));
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", undefined, on_deleteDirectory_error);
+    root.deleteDirectory(cb.successCallback, cb.errorCallback, dir.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-103
+// Parameters: directory = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_deleteDirectory_error_103() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("deleteDirectory()", (err.code == INVALID_VALUES_ERR));
+      deleteDirectory(root, dir);
+    }
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", false);
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+    root.deleteDirectory(cb.successCallback, cb.errorCallback, undefined, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-104
+// Parameters: recursive = undefined, others = valid
+// Result: Test passes.
+function test_file_deleteDirectory_error_104() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("deleteDirectory()", false);
+      deleteDirectory(root, dir);
+    }
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", true);
+    }
+    
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+    root.deleteDirectory(cb.successCallback, cb.errorCallback, dir.fullPath, undefined);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-105: Call deleteDirectory() with directory parameter pointing to a file.
+function test_file_deleteDirectory_error_105() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_deleteDirectory_error(err) {
+      TestEngine.test("deleteDirectory() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    function on_deleteDirectory_success() {
+      TestEngine.test("deleteDirectory()", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("deleteDirectory", on_deleteDirectory_success, on_deleteDirectory_error);
+    root.deleteDirectory(cb.successCallback, cb.errorCallback, file.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-106: Call deleteFile() with error callback set to null.
+function test_file_deleteFile_106() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_deleteFile_success() {
+      TestEngine.test("deleteFile()", true);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, null);
+    root.deleteFile(cb.successCallback, null, file.fullPath);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-107: Call deleteFile() with error callback set to null
+//                     and file set to invalid value.
+function test_file_deleteFile_error_107() {
+  function on_resolve_success(root) {
+    function on_deleteFile_success() {
+      TestEngine.test("deleteFile()", false);
+    }
+    testNoExceptionWithMessage("deleteFile()", function() {
+      // Pass callbacks directly to prevent "widget run timeout".
+      root.deleteFile(on_deleteFile_success, null, "../");
+    });
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-108: Call deleteFile() with success callback set to null.
+function test_file_deleteFile_error_108() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_deleteFile_error(err) {
+      TestEngine.test("deleteFile() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", null, on_deleteFile_error);
+    root.deleteFile(null, cb.errorCallback, file.fullPath);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-109
+// Parameters: successCallback = undefined, others valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_deleteFile_error_109() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_deleteFile_error(err) {
+      TestEngine.test("deleteFile()", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", undefined, on_deleteFile_error);
+    root.deleteFile(cb.successCallback, cb.errorCallback, file.fullPath);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-110
+// Parameters: file = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_deleteFile_error_110() {
+  function on_resolve_success(root) {
+    function on_deleteFile_error(err) {
+      TestEngine.test("deleteFile()", (err.code == INVALID_VALUES_ERR));
+    }
+    function on_deleteFile_success() {
+      TestEngine.test("deleteFile()", false);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, on_deleteFile_error);
+    root.deleteFile(cb.successCallback, cb.errorCallback, undefined);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-111
+// Parameters: errorCallback = undefined, others = valid
+// Result: Test passes.
+function test_file_deleteFile_error_111() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_deleteFile_success() {
+      TestEngine.test("deleteFile()", true);
+    }
+    var cb = TestEngine.registerCallback("deleteFile", on_deleteFile_success, undefined);
+    root.deleteFile(cb.successCallback, cb.errorCallback, file.fullPath);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-112
+// Parameters: mode = undefined, others = valid
+// Result: Test passes.
+function test_filesystem_resolve_112() {
+  function on_resolve_error(err) {
+   TestEngine.test("resolve() [" + err.code + "]", false);
+  }
+  function on_resolve_success(root) {
+   TestEngine.test("resolve()", true);
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION, undefined);
+}
+
+// WAC-FILESYSTEM-113
+// Parameters: encoding = undefined, others = valid
+// Result: Test passes.
+function test_file_readAsText_113() {
+  var test_content = "Ala ma kota";
+  function on_resolve_success(root) {
+    var file = createFileForParent(root)
+
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.write(test_content);
+      stream.close();
+
+      function on_readAsText_error(err) {
+        TestEngine.test("readAsText() [" + err.code + "]", false);
+        deleteFile(root, file);
+      }
+      function on_readAsText_success(str) {
+        TestEngine.test("readAsText()", (str === test_content));
+        deleteFile(root, file);
+      }
+      var cb = TestEngine.registerCallback("readAsText", on_readAsText_success, on_readAsText_error);
+      file.readAsText(cb.successCallback, cb.errorCallback, undefined);
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-114
+// Parameters: encoding = undefined, others = valid
+// Result: INVALID_VALUES_ERR thrown via error callback.
+function test_file_open_114() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    function on_openStream_error(err) {
+      TestEngine.test("openStream()", (err.code == INVALID_VALUES_ERR));
+      deleteFile(root, file);
+    }
+    function on_openStream_success(stream) {
+      TestEngine.test("openStream()", false);
+      stream.close();
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    var stream = file.openStream(cb.successCallback, cb.errorCallback, "r", undefined);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-115
+// Parameters: originFilePath = (empty) directory, overwrite = false
+// Result: Test passes.
+function test_file_copyTo_115() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteDirectory(root, dir);
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", isDir(copy));
+      deleteDirectory(root, copy);
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, dir.fullPath, root.fullPath + "/" + getDirName(), false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-116
+// Parameters: originFilePath = (non-empty) directory, overwrite = false
+// Result: Test passes.
+function test_file_copyTo_116() {
+  function on_resolve_success(root) {
+    var dir = createDirForParent(root);
+    var file = createFileForParent(dir);
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteDirectory(root, dir);
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", isDir(copy));
+      var child = copy.resolve(file.name);
+      TestEngine.test("copyTo()", isFile(child));
+      deleteDirectory(root, copy);
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, dir.fullPath, root.fullPath + "/" + getDirName(), false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-117
+// Parameters: originFilePath = undefined, other params = valid.
+// Result: INVALID_VALUES_ERR thrown via errorCallback.
+function test_file_copyTo_error_117() {
+  function on_resolve_success(root) {
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo()", (err.code == INVALID_VALUES_ERR));
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", false);
+      deleteDirectory(root, copy);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, undefined, root.fullPath + "/" + getDirName(), false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-118
+// Parameters: originFilePath = invalid path, overwrite = false
+// Result: INVALID_VALUES_ERR returned by error callback.
+function test_file_copyTo_error_118() {
+  function on_resolve_success(root) {
+   function on_copyTo_error(err) {
+     TestEngine.test("copyTo() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+   }
+   function on_copyTo_success(copy) {
+     TestEngine.test("copyTo()", false);
+     deleteDirectory(root, copy);
+   }
+   var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+   root.copyTo(cb.successCallback, cb.errorCallback, "../", root.fullPath + "/" + getDirName(), false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-119
+// Parameters: originFilePath = valid file, destinationFilePath = valid directory, overwrite = true
+// Result: Test passes (replacing destination directory with a origin file).
+function test_file_copyTo_119() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    var dir = createDirForParent(root);
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteDirectory(root, dir);
+      deleteFile(root, file);
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", (copy.fullPath == dir.fullPath) && isFile(copy));
+      deleteFile(root, copy);
+      deleteFile(root, file);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, file.fullPath, dir.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-120
+// Parameters: originFilePath = valid file, destinationFilePath = valid directory, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_copyTo_error_120() {
+  function on_resolve_success(root) {
+   var file = createFileForParent(root);
+   var dir = createDirForParent(root);
+   function on_copyTo_error(err) {
+     TestEngine.test("copyTo() [" + err.code + "]", (err.code == IO_ERR));
+     deleteDirectory(root, dir);
+     deleteFile(root, file);
+   }
+   function on_copyTo_success(copy) {
+     TestEngine.test("copyTo()", false);
+     deleteFile(root, copy);
+     deleteFile(root, file);
+   }
+   var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+   root.copyTo(cb.successCallback, cb.errorCallback, file.fullPath, dir.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-121
+// Parameters: originFilePath = valid directory, destinationFilePath = valid file, overwrite = true
+// Result: Test passes (replacing destination file with a origin directory).
+function test_file_copyTo_121() {
+  function on_resolve_success(root) {
+   var file = createFileForParent(root);
+   var dir = createDirForParent(root);
+   var child = createFileForParent(dir);
+   function on_copyTo_error(err) {
+     TestEngine.test("copyTo() [" + err.code + "]", false);
+     deleteDirectory(root, dir);
+     deleteFile(root, file);
+   }
+   function on_copyTo_success(copy) {
+     TestEngine.test("copyTo()", (copy.fullPath == file.fullPath) && isDir(copy));
+     TestEngine.test("resolve()", isFile(copy.resolve(child.name)));
+     deleteDirectory(root, copy);
+     deleteDirectory(root, dir);
+   }
+   var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+   root.copyTo(cb.successCallback, cb.errorCallback, dir.fullPath, file.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-122
+// Parameters: originFilePath = valid directory, destinationFilePath = valid file, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_copyTo_error_122() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    var dir = createDirForParent(root);
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteDirectory(root, dir);
+      deleteFile(root, file);
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", false);
+      deleteDirectory(root, copy);
+      deleteDirectory(root, dir);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, dir.fullPath, file.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-123
+// Parameters: originFilePath = valid directory, destinationFilePath = valid directory, overwrite = true
+// Result: Test passes (replacing destination directory with a origin directory).
+function test_file_copyTo_123() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var dest = createDirForParent(root);
+    var child = createFileForParent(src);
+    function on_copyTo_error(err) {
+      TestEngine.test("copyTo() [" + err.code + "]", false);
+      deleteDirectory(root, src);
+      deleteDirectory(root, dest);
+    }
+    function on_copyTo_success(copy) {
+      TestEngine.test("copyTo()", (copy.fullPath == dest.fullPath) && isDir(copy));
+      TestEngine.test("resolve()", isFile(copy.resolve(child.name)));
+      deleteDirectory(root, copy);
+      deleteDirectory(root, src);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-124
+// Parameters: originFilePath = valid directory, destinationFilePath = valid directory, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_copyTo_error_124() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var dest = createDirForParent(root);
+    function on_copyTo_error(err) {
+     TestEngine.test("copyTo() [" + err.code + "]", (err.code == IO_ERR));
+     deleteDirectory(root, src);
+     deleteDirectory(root, dest);
+    }
+    function on_copyTo_success(copy) {
+     TestEngine.test("copyTo()", false);
+     deleteDirectory(root, copy);
+     deleteDirectory(root, src);
+    }
+    var cb = TestEngine.registerCallback("copyTo", on_copyTo_success, on_copyTo_error);
+    root.copyTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-125
+// Parameters: originFilePath = (empty) directory, overwrite = false
+// Result: Test passes.
+function test_file_moveTo_125() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var dest = root.fullPath + "/" + getDirName();
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", false);
+      deleteDirectory(root, src);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", isDir(result));
+      TestEngine.testPresetError(
+        "resolve() [NOT_FOUND_ERR]",
+        function() { root.resolve(src.name) },
+        NOT_FOUND_ERR
+      );
+      deleteDirectory(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-126
+// Parameters: originFilePath = (non-empty) directory, overwrite = false
+// Result: Test passes.
+function test_file_moveTo_126() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var file = createFileForParent(src);
+    var dest = root.fullPath + "/" + getDirName();
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", false);
+      deleteDirectory(root, src);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", isDir(result));
+      var child = result.resolve(file.name);
+      TestEngine.test("resolve()", isFile(child));
+      TestEngine.testPresetError(
+        "resolve() [NOT_FOUND_ERR]",
+        function() { root.resolve(src.name) },
+        NOT_FOUND_ERR
+      );
+      deleteDirectory(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-127
+// Parameters: originFilePath = undefined, other params = valid.
+// Result: INVALID_VALUES_ERR thrown via errorCallback.
+function test_file_moveTo_error_127() {
+  function on_resolve_success(root) {
+    var dest = root.fullPath + "/" + getDirName();
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo()", (err.code == INVALID_VALUES_ERR));
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, undefined, dest, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-128
+// Parameters: originFilePath = invalid path, overwrite = false
+// Result: INVALID_VALUES_ERR returned by error callback.
+function test_file_moveTo_error_128() {
+  function on_resolve_success(root) {
+    var src = "../";
+    var dest = root.fullPath + "/" + getDirName();
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == INVALID_VALUES_ERR));
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src, dest, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-129
+// Parameters: originFilePath = valid file, destinationFilePath = valid directory, overwrite = true
+// Result: IO_ERR passed via error callback.
+function test_file_moveTo_129() {
+  function on_resolve_success(root) {
+    var src = createFileForParent(root);
+    var dest = createDirForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteFile(root, src);
+      deleteDirectory(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+      deleteFile(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-130
+// Parameters: originFilePath = valid file, destinationFilePath = valid directory, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_moveTo_error_130() {
+  function on_resolve_success(root) {
+    var src = createFileForParent(root);
+    var dest = createDirForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteFile(root, src);
+      deleteDirectory(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+      deleteFile(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-131
+// Parameters: originFilePath = valid directory, destinationFilePath = valid file, overwrite = true
+// Result: IO_ERR passed via error callback.
+function test_file_moveTo_131() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var child = createFileForParent(src);
+    var dest = createFileForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteDirectory(root, src);
+      deleteFile(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+      deleteFile(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-132
+// Parameters: originFilePath = valid directory, destinationFilePath = valid file, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_moveTo_error_132() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var child = createFileForParent(src);
+    var dest = createFileForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteDirectory(root, src);
+      deleteFile(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+      deleteDirectory(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-133
+// Parameters: originFilePath = valid directory, destinationFilePath = valid directory, overwrite = true
+// Result: Test passes (replacing destination directory with a origin directory).
+function test_file_moveTo_133() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var child = createFileForParent(src);
+    var dest = createDirForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", false);
+      deleteDirectory(root, src);
+      deleteDirectory(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", (result.fullPath == dest.fullPath) && isDir(result));
+      TestEngine.test("resolve()", isFile(result.resolve(child.name)));
+      TestEngine.testPresetError(
+        "resolve() [NOT_FOUND_ERR]",
+        function() { root.resolve(src.name); },
+        NOT_FOUND_ERR
+      );
+      deleteDirectory(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, true);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-134
+// Parameters: originFilePath = valid directory, destinationFilePath = valid directory, overwrite = false
+// Result: IO_ERR passed via error callback.
+function test_file_moveTo_error_134() {
+  function on_resolve_success(root) {
+    var src = createDirForParent(root);
+    var child = createFileForParent(src);
+    var dest = createDirForParent(root);
+    function on_moveTo_error(err) {
+      TestEngine.test("moveTo() [" + err.code + "]", (err.code == IO_ERR));
+      deleteDirectory(root, src);
+      deleteDirectory(root, dest);
+    }
+    function on_moveTo_success(result) {
+      TestEngine.test("moveTo()", false);
+      deleteDirectory(root, result);
+    }
+    var cb = TestEngine.registerCallback("moveTo", on_moveTo_success, on_moveTo_error);
+    root.moveTo(cb.successCallback, cb.errorCallback, src.fullPath, dest.fullPath, false);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-135
+// Parameters: filePath = valid path to an existing file
+// Result: Test passes.
+function test_file_resolve_135() {
+  function on_resolve_success(root) {
+    var file = createFileForParent(root);
+    var resolved = root.resolve(file.name);
+    TestEngine.test("resolve()", isFile(resolved) && (file.fullPath == resolved.fullPath));
+    deleteFile(root, file);
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-136
+// Parameters: filePath = valid path to non-existing file
+// Result: NOT_FOUND_ERR thrown in place.
+function test_file_resolve_error_136() {
+  function on_resolve_success(root) {
+    var fileNotExist = getFileName();
+    TestEngine.testPresetError(
+      "resolve() [NOT_FOUND_ERR]",
+      function() { root.resolve(fileNotExist); },
+      NOT_FOUND_ERR
+    );
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-137
+// Parameters: filePath = invalid path
+// Result: NOT_FOUND_ERR thrown in place.
+function test_file_resolve_error_137() {
+  function on_resolve_success(root) {
+   var invalidPath = "../";
+   TestEngine.testPresetError(
+     "resolve() [INVALID_VALUES_ERR]",
+     function() { root.resolve(invalidPath); },
+     INVALID_VALUES_ERR
+   );
+  }
+  resolve_root_location(on_resolve_success);
+}
+
+// WAC-FILESYSTEM-138: Open file in append mode and test append mode.
+function test_file_append_behaviour_138() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) {
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    function on_openStream_success(stream) {
+      function on_openStream_success2(stream) {
+        function on_openStream_success3(stream) {
+            var array = stream.readBytes(4);
+            TestEngine.test("readBytes(4)", array.length === 4);
+            TestEngine.test("array[0]", array[0] === 1);
+            TestEngine.test("array[1]", array[1] === 2);
+            TestEngine.test("array[2]", array[2] === 3);
+            TestEngine.test("array[3]", array[3] === 4);
+            stream.close();
+            deleteFile(file, file2);
+        }
+        TestEngine.test("openStream()", isFilestream(stream));
+        stream.writeBytes([3, 4]);
+        stream.close();
+        //reopen in read mode
+        var cb = TestEngine.registerCallback("openStream", on_openStream_success3, on_openStream_error);
+        file2.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+      }
+      TestEngine.test("openStream()", isFilestream(stream));
+      stream.writeBytes([1, 2]);
+      stream.close();
+      //reopen again in append mode
+      var cb = TestEngine.registerCallback("openStream", on_openStream_success2, on_openStream_error);
+      file2.openStream(cb.successCallback, cb.errorCallback, "a", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var cb = TestEngine.registerCallback("openStream", on_openStream_success, on_openStream_error);
+    file2.openStream(cb.successCallback, cb.errorCallback, "a", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC-FILESYSTEM-139: Set postion.
+function test_file_set_position_139() {
+  function on_resolve_error(err) {
+      TestEngine.test("resolve() [" + err.code + "]", false);
+  }
+  function on_resolve_success(file) {
+    function on_openStream_success(stream) {
+      function on_openStream_success2(stream) {
+        TestEngine.test("Correct postion after opening",
+            stream.position === 0);
+        var array = stream.readBytes(5);
+        TestEngine.test("Correct number of bytes read", array.length === 4);
+        TestEngine.test("Correct values of bytes read", array[0] === 5 &&
+            array[1] === 6 && array[2] === 7 && array[3] === 8);
+        stream.position = 2;
+        array = stream.readBytes(1);
+        TestEngine.test("Correct values of bytes read at pos 2",
+            array.length === 1 && array[0] === 7);
+        stream.position = 1;
+        array = stream.readBytes(1);
+        TestEngine.test("Correct values of bytes read at pos 1",
+            array.length === 1 && array[0] === 6);
+        stream.position = 0;
+        array = stream.readBytes(1);
+        TestEngine.test("Correct values of bytes read at pos 0",
+            array.length === 1 && array[0] === 5);
+        stream.position = 3;
+        array = stream.readBytes(1);
+        TestEngine.test("Correct values of bytes read at pos 3",
+            array.length === 1 && array[0] === 8);
+        stream.close();
+        deleteFile(file, file2);
+      }
+      TestEngine.test("openStream()", isFilestream(stream));
+      TestEngine.test("Correct postion after opening",
+          stream.position === 0);
+      stream.writeBytes([1, 2, 3, 4]);
+      TestEngine.test("Correct postion after write ", stream.position === 4);
+      stream.position = 0;
+      TestEngine.test("Correct postion after setting postion",
+          stream.position === 0);
+      stream.writeBytes([5, 6, 7, 8]);
+      stream.close();
+      var cb = TestEngine.registerCallback("openStream",
+          on_openStream_success2, on_openStream_error);
+      file2.openStream(cb.successCallback, cb.errorCallback, "r", "UTF-8");
+    }
+    function on_openStream_error(err) {
+      TestEngine.test("openStream() [" + err.code + "]", false);
+    }
+    var file2 = file.createFile(getFileName());
+    TestEngine.test("createFile()", isFile(file2));
+    var cb = TestEngine.registerCallback("openStream",
+        on_openStream_success, on_openStream_error);
+    file2.openStream(cb.successCallback, cb.errorCallback, "w", "UTF-8");
+  }
+  resolve_root(on_resolve_success, on_resolve_error);
+}
+
+// WAC2-FILESYSTEM-140: Resolve wgt-package in rw mode.
+// Result: UNKNOWN_ERR thrown via error callback.
+function test_filesystem_resolve_error_140() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", (err.code == UNKNOWN_ERR)); }
+  function on_resolve_success(file) { TestEngine.test("resolve()", false);}
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, 'wgt-package', 'rw');
+}
+
+// WAC2-FILESYSTEM-141: Resolve wgt-package/config.xml in rw mode.
+// Result: UNKNOWN_ERR thrown via error callback.
+function test_filesystem_resolve_error_141() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", (err.code == UNKNOWN_ERR)); }
+  function on_resolve_success(file) { TestEngine.test("resolve()", false);}
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, 'wgt-package/config.xml', 'rw');
+}
+
+// WAC2-FILESYSTEM-142: Resolve wgt-package in r mode.
+// Result: Success.
+function test_filesystem_resolve_142() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) { TestEngine.test("resolve()", isFileObject(file));}
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, 'wgt-package', 'r');
+}
+// WAC2-FILESYSTEM-143: Resolve wgt-package/config.xml in r mode.
+// Result: Success.
+function test_filesystem_resolve_143() {
+  function on_resolve_error(err) { TestEngine.test("resolve() [" + err.code + "]", false); }
+  function on_resolve_success(file) { TestEngine.test("resolve()", isFileObject(file));}
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, 'wgt-package/config.xml', 'r');
+}
+
+//=============================================================================
+TestEngine.setTestSuiteName("[WAC2.0][Filesystem]");
+//TestEngine.addTest(true, test_filesystem_properties_001, "WAC-FILESYSTEM-001");
+//TestEngine.addTest(true, test_filesystem_resolve_002, "WAC-FILESYSTEM-002");
+//TestEngine.addTest(true, test_filesystem_resolve_003, "WAC-FILESYSTEM-003");
+//TestEngine.addTest(true, test_file_listFiles_004, "WAC-FILESYSTEM-004");
+//TestEngine.addTest(true, test_file_open_005, "WAC-FILESYSTEM-005");
+//TestEngine.addTest(true, test_file_open_006, "WAC-FILESYSTEM-006");
+//TestEngine.addTest(true, test_file_open_007, "WAC-FILESYSTEM-007");
+//TestEngine.addTest(true, test_file_open_error_008, "WAC-FILESYSTEM-008");
+//TestEngine.addTest(true, test_file_open_error_009, "WAC-FILESYSTEM-009");
+//TestEngine.addTest(true, test_file_copyTo_010, "WAC-FILESYSTEM-010");
+//TestEngine.addTest(true, test_file_copyTo_error_011, "WAC-FILESYSTEM-011");
+//TestEngine.addTest(true, test_file_copyTo_012, "WAC-FILESYSTEM-012");
+//TestEngine.addTest(true, test_file_createFile_013, "WAC-FILESYSTEM-013");
+//TestEngine.addTest(true, test_file_createFile_error_014, "WAC-FILESYSTEM-014");
+//TestEngine.addTest(true, test_file_createFile_error_015, "WAC-FILESYSTEM-015");
+//TestEngine.addTest(true, test_file_createFile_error_016, "WAC-FILESYSTEM-016");
+//TestEngine.addTest(true, test_file_createFile_error_017, "WAC-FILESYSTEM-017");
+//TestEngine.addTest(true, test_file_createDirectory_018, "WAC-FILESYSTEM-018");
+//TestEngine.addTest(true, test_file_createDirectory_error_019, "WAC-FILESYSTEM-019");
+//TestEngine.addTest(true, test_file_createDirectory_error_020, "WAC-FILESYSTEM-020");
+//TestEngine.addTest(true, test_file_createDirectory_error_021, "WAC-FILESYSTEM-021");
+//TestEngine.addTest(true, test_file_createDirectory_error_022, "WAC-FILESYSTEM-022");
+//TestEngine.addTest(true, test_file_moveTo_023, "WAC-FILESYSTEM-023");
+//TestEngine.addTest(true, test_file_moveTo_error_024, "WAC-FILESYSTEM-024");
+//TestEngine.addTest(true, test_file_moveTo_025, "WAC-FILESYSTEM-025");
+//TestEngine.addTest(true, test_file_deleteFile_026, "WAC-FILESYSTEM-026");
+//TestEngine.addTest(true, test_file_deleteFile_error_027, "WAC-FILESYSTEM-027");
+//TestEngine.addTest(true, test_file_deleteFile_error_028, "WAC-FILESYSTEM-028");
+//TestEngine.addTest(true, test_file_deleteFile_error_029, "WAC-FILESYSTEM-029");
+//TestEngine.addTest(true, test_file_deleteFile_error_030, "WAC-FILESYSTEM-030");
+//TestEngine.addTest(true, test_file_deleteDirectory_031, "WAC-FILESYSTEM-031");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_032, "WAC-FILESYSTEM-032");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_033, "WAC-FILESYSTEM-033");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_034, "WAC-FILESYSTEM-034");
+//TestEngine.addTest(true, test_filestream_write_read_035, "WAC-FILESYSTEM-035");
+TestEngine.addTest(true, test_filestream_read_error_036, "WAC-FILESYSTEM-036");
+//TestEngine.addTest(true, test_filestream_read_error_037, "WAC-FILESYSTEM-037");
+//TestEngine.addTest(true, test_file_open_error_038, "WAC-FILESYSTEM-038");
+//TestEngine.addTest(true, test_filestream_read_error_040, "WAC-FILESYSTEM-040");
+//TestEngine.addTest(true, test_filestream_write_error_041, "WAC-FILESYSTEM-041");
+//TestEngine.addTest(true, test_filestream_write_error_042, "WAC-FILESYSTEM-042");
+//TestEngine.addTest(true, test_filestream_write_error_043, "WAC-FILESYSTEM-043");
+//TestEngine.addTest(true, test_filestream_write_error_044, "WAC-FILESYSTEM-044");
+//TestEngine.addTest(true, test_filestream_read_error_045, "WAC-FILESYSTEM-045");
+//TestEngine.addTest(true, test_filestream_read_error_046, "WAC-FILESYSTEM-046");
+//TestEngine.addTest(true, test_filestream_writeBytes_readBytes_047, "WAC-FILESYSTEM-047");
+//TestEngine.addTest(true, test_filestream_readBytes_error_048, "WAC-FILESYSTEM-048");
+//TestEngine.addTest(true, test_filestream_readBytes_error_049, "WAC-FILESYSTEM-049");
+//TestEngine.addTest(true, test_filestream_readBytes_error_051, "WAC-FILESYSTEM-051");
+//TestEngine.addTest(true, test_filestream_readBytes_error_052, "WAC-FILESYSTEM-052");
+//TestEngine.addTest(true, test_filestream_readBytes_error_053, "WAC-FILESYSTEM-053");
+//TestEngine.addTest(true, test_filestream_writeBytes_error_054, "WAC-FILESYSTEM-054");
+//TestEngine.addTest(true, test_filestream_writeBytes_error_055, "WAC-FILESYSTEM-055");
+//TestEngine.addTest(true, test_filestream_writeBytes_error_056, "WAC-FILESYSTEM-056");
+//TestEngine.addTest(true, test_filestream_writeBytes_057, "WAC-FILESYSTEM-057");
+//TestEngine.addTest(true, test_filestream_writeBase64_readBase64_058, "WAC-FILESYSTEM-058");
+//TestEngine.addTest(true, test_filestream_writeBase64_read_059, "WAC-FILESYSTEM-059");
+//TestEngine.addTest(true, test_filestream_write_readBase64_060, "WAC-FILESYSTEM-060");
+//TestEngine.addTest(true, test_filestream_readBase64_error_061, "WAC-FILESYSTEM-061");
+//TestEngine.addTest(true, test_filestream_readBase64_error_062, "WAC-FILESYSTEM-062");
+//TestEngine.addTest(true, test_filestream_readBase64_error_064, "WAC-FILESYSTEM-064");
+//TestEngine.addTest(true, test_filestream_readBase64_error_065, "WAC-FILESYSTEM-065");
+//TestEngine.addTest(true, test_filestream_readBase64_error_066, "WAC-FILESYSTEM-066");
+//TestEngine.addTest(true, test_filestream_writeBase64_error_067, "WAC-FILESYSTEM-067");
+//TestEngine.addTest(true, test_filestream_writeBase64_error_068, "WAC-FILESYSTEM-068");
+//TestEngine.addTest(true, test_filestream_writeBase64_error_069, "WAC-FILESYSTEM-069");
+//TestEngine.addTest(true, test_filestream_writeBase64_error_070, "WAC-FILESYSTEM-070");
+//TestEngine.addTest(true, test_file_createFile_error_071, "WAC-FILESYSTEM-071");
+//TestEngine.addTest(true, test_file_deleteFile_error_072, "WAC-FILESYSTEM-072");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_073, "WAC-FILESYSTEM-073");
+//TestEngine.addTest(true, test_file_moveTo_error_074, "WAC-FILESYSTEM-074");
+//TestEngine.addTest(true, test_file_openStream_error_075, "WAC-FILESYSTEM-075");
+//TestEngine.addTest(true, test_file_readAsText_076, "WAC-FILESYSTEM-076");
+//TestEngine.addTest(true, test_file_readAsText_error_077, "WAC-FILESYSTEM-077");
+//TestEngine.addTest(true, test_file_readAsText_error_078, "WAC-FILESYSTEM-078");
+//TestEngine.addTest(true, test_file_toUri_079, "WAC-FILESYSTEM-079");
+//TestEngine.addTest(true, test_filesystem_resolve_080, "WAC-FILESYSTEM-080");
+//TestEngine.addTest(true, test_file_listFiles_081, "WAC-FILESYSTEM-081");
+//TestEngine.addTest(true, test_file_listFiles_082, "WAC-FILESYSTEM-082");
+//TestEngine.addTest(true, test_file_listFiles_error_083, "WAC-FILESYSTEM-083");
+//TestEngine.addTest(true, test_file_listFiles_error_084, "WAC-FILESYSTEM-084");
+//TestEngine.addTest(true, test_file_listFiles_error_085, "WAC-FILESYSTEM-085");
+//TestEngine.addTest(true, test_file_listFiles_error_086, "WAC-FILESYSTEM-086");
+//TestEngine.addTest(true, test_file_open_087, "WAC-FILESYSTEM-087");
+//TestEngine.addTest(true, test_file_open_error_088, "WAC-FILESYSTEM-088");
+//TestEngine.addTest(true, test_file_open_error_089, "WAC-FILESYSTEM-089");
+//TestEngine.addTest(true, test_file_open_error_090, "WAC-FILESYSTEM-090");
+//TestEngine.addTest(true, test_file_readAsText_091, "WAC-FILESYSTEM-091");
+//TestEngine.addTest(true, test_file_readAsText_092, "WAC-FILESYSTEM-092");
+//TestEngine.addTest(true, test_file_readAsText_093, "WAC-FILESYSTEM-093");
+//TestEngine.addTest(true, test_file_readAsText_094, "WAC-FILESYSTEM-094");
+//TestEngine.addTest(true, test_file_readAsText_error_095, "WAC-FILESYSTEM-095");
+//TestEngine.addTest(true, test_file_readAsText_error_096, "WAC-FILESYSTEM-096");
+//TestEngine.addTest(true, test_file_readAsText_error_097, "WAC-FILESYSTEM-097");
+//TestEngine.addTest(true, test_file_readAsText_error_098, "WAC-FILESYSTEM-098");
+//TestEngine.addTest(true, test_file_deleteDirectory_099, "WAC-FILESYSTEM-099");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_100, "WAC-FILESYSTEM-100");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_101, "WAC-FILESYSTEM-101");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_102, "WAC-FILESYSTEM-102");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_103, "WAC-FILESYSTEM-103");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_104, "WAC-FILESYSTEM-104");
+//TestEngine.addTest(true, test_file_deleteDirectory_error_105, "WAC-FILESYSTEM-105");
+//TestEngine.addTest(true, test_file_deleteFile_106, "WAC-FILESYSTEM-106");
+//TestEngine.addTest(true, test_file_deleteFile_error_107, "WAC-FILESYSTEM-107");
+//TestEngine.addTest(true, test_file_deleteFile_error_108, "WAC-FILESYSTEM-108");
+//TestEngine.addTest(true, test_file_deleteFile_error_109, "WAC-FILESYSTEM-109");
+//TestEngine.addTest(true, test_file_deleteFile_error_110, "WAC-FILESYSTEM-110");
+//TestEngine.addTest(true, test_file_deleteFile_error_111, "WAC-FILESYSTEM-111");
+//TestEngine.addTest(true, test_filesystem_resolve_112, "WAC-FILESYSTEM-112");
+//TestEngine.addTest(true, test_file_readAsText_113, "WAC-FILESYSTEM-113");
+//TestEngine.addTest(true, test_file_open_114, "WAC-FILESYSTEM-114");
+//TestEngine.addTest(true, test_file_copyTo_115, "WAC-FILESYSTEM-115");
+//TestEngine.addTest(true, test_file_copyTo_116, "WAC-FILESYSTEM-116");
+//TestEngine.addTest(true, test_file_copyTo_error_117, "WAC-FILESYSTEM-117");
+//TestEngine.addTest(true, test_file_copyTo_error_118, "WAC-FILESYSTEM-118");
+//TestEngine.addTest(true, test_file_copyTo_119, "WAC-FILESYSTEM-119");
+//TestEngine.addTest(true, test_file_copyTo_error_120, "WAC-FILESYSTEM-120");
+//TestEngine.addTest(true, test_file_copyTo_121, "WAC-FILESYSTEM-121");
+//TestEngine.addTest(true, test_file_copyTo_error_122, "WAC-FILESYSTEM-122");
+//TestEngine.addTest(true, test_file_copyTo_123, "WAC-FILESYSTEM-123");
+//TestEngine.addTest(true, test_file_copyTo_error_124, "WAC-FILESYSTEM-124");
+//TestEngine.addTest(true, test_file_moveTo_125, "WAC-FILESYSTEM-125");
+//TestEngine.addTest(true, test_file_moveTo_126, "WAC-FILESYSTEM-126");
+//TestEngine.addTest(true, test_file_moveTo_error_127, "WAC-FILESYSTEM-127");
+//TestEngine.addTest(true, test_file_moveTo_error_128, "WAC-FILESYSTEM-128");
+//TestEngine.addTest(true, test_file_moveTo_129, "WAC-FILESYSTEM-129");
+//TestEngine.addTest(true, test_file_moveTo_error_130, "WAC-FILESYSTEM-130");
+//TestEngine.addTest(true, test_file_moveTo_131, "WAC-FILESYSTEM-131");
+//TestEngine.addTest(true, test_file_moveTo_error_132, "WAC-FILESYSTEM-132");
+//TestEngine.addTest(true, test_file_moveTo_133, "WAC-FILESYSTEM-133");
+//TestEngine.addTest(true, test_file_moveTo_error_134, "WAC-FILESYSTEM-134");
+//TestEngine.addTest(true, test_file_resolve_135, "WAC-FILESYSTEM-135");
+//TestEngine.addTest(true, test_file_resolve_error_136, "WAC-FILESYSTEM-136");
+//TestEngine.addTest(true, test_file_resolve_error_137, "WAC-FILESYSTEM-137");
+//TestEngine.addTest(true, test_file_append_behaviour_138, "WAC-FILESYSTEM-138");
+//TestEngine.addTest(true, test_file_set_position_139, "WAC-FILESYSTEM-139");
+//TestEngine.addTest(true, test_filesystem_resolve_error_140, "WAC-FILESYSTEM-140");
+//TestEngine.addTest(true, test_filesystem_resolve_error_141, "WAC-FILESYSTEM-141");
+//TestEngine.addTest(true, test_filesystem_resolve_142, "WAC-FILESYSTEM-142");
+//TestEngine.addTest(true, test_filesystem_resolve_143, "WAC-FILESYSTEM-143");
+
+//=============================================================================
+// --------------------------| Utilities
+
+function isFileObject(obj) {
+  return (obj instanceof deviceapis.filesystem.File);
+}
+
+function isFile(obj) {
+  return (isFileObject(obj) && !obj.isDirectory);
+}
+
+function isDir(obj) {
+  return (isFileObject(obj) && obj.isDirectory);
+}
+
+function isFilestream(obj) {
+  return (obj instanceof deviceapis.filesystem.FileStream);
+}
+
+function deleteDirectory(parent, dir) {
+  function on_error(err) {
+    TestEngine.test("deleteDirectory() [" + err.code + "]", false);
+  }
+  function on_success() {
+    TestEngine.test("deleteDirectory()", true);
+  }
+  var cb = TestEngine.registerCallback("deleteDirectory", on_success, on_error);
+  parent.deleteDirectory(cb.successCallback, cb.errorCallback, dir.fullPath, true);
+}
+
+function deleteFile(parent, file) {
+  function on_error(err) {
+    TestEngine.test("deleteFile() [" + err.code + "]", false);
+  }
+  function on_success() {
+    TestEngine.test("deleteFile()", true);
+  }
+  var cb = TestEngine.registerCallback("deleteFile", on_success, on_error);
+  parent.deleteFile(cb.successCallback, cb.errorCallback, file.fullPath);
+}
+
+// For common behaviour use resolve_root_location
+function resolve_root(on_success_callback, on_error_callback) {
+  var cb = TestEngine.registerCallback("resolve", on_success_callback, on_error_callback);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION);
+}
+
+function resolve_root_location(handler) {
+  function on_resolve_error(err) {
+    TestEngine.test("resolve() [" + err.code + "]", false);
+  }
+  function on_resolve_success(file) {
+    TestEngine.test("resolve()", isFileObject(file));
+    handler(file);
+  }
+  var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+  deviceapis.filesystem.resolve(cb.successCallback, cb.errorCallback, TEST_ROOT_LOCATION);
+}
+
+var counter = 1;
+
+function getFileName() {
+  var nr = Math.floor(Math.random() * 1000);
+  var date = new Date();
+  return "test_wac20_filesystem_file_" + nr + "_" + (counter++) + "_"
+         + date.getMinutes() + date.getSeconds() + date.getMilliseconds();
+}
+
+function getDirName() {
+  var nr = Math.floor(Math.random() * 1000);
+  var date = new Date();
+  return "test_wac20_filesystem_dir_" + nr + "_" + (counter++) + "_"
+         + date.getMinutes() + date.getSeconds() + date.getMilliseconds();
+}
+
+function createFileForParent(parent) {
+  var result = parent.createFile(getFileName());
+  TestEngine.test("createFile()", isFile(result));
+  return result;
+}
+
+function createDirForParent(parent) {
+  var result = parent.createDirectory(getDirName());
+  TestEngine.test("createDirectory()", isDir(result));
+  return result;
+}
+
+function testNoExceptionWithMessage(message, fun) {
+  var testResult = true;
+  try {
+    fun();
+  }
+  catch (e) {
+    testResult = false;
+  }
+  TestEngine.test(message, testResult);
+}
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestGeolocation.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestGeolocation.js
new file mode 100644 (file)
index 0000000..418ef3e
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+function presenceTest()
+{
+    TestEngine.test("Checking checking", true);
+    TestEngine.test("Checking Geolocation object", navigator.geolocation);
+
+    TestEngine.test("Checking function getCurrentPosition",
+        isFunction(navigator.geolocation.getCurrentPosition));
+}
+
+function accessTest()
+{
+    try {
+        jsPrint("DEBUG POINT 0");
+        var callbackObject = TestEngine.registerCallback("getCurrentPositionCallback",
+                                                         localSuccessCallback,
+                                                         localErrorCallback);
+        jsPrint("DEBUG POINT 1");
+        navigator.geolocation.getCurrentPosition(
+            callbackObject.successCallback,
+            callbackObject.errorCallback);
+        jsPrint("DEBUG POINT 2");
+    } catch (error) {
+        jsPrint("DEBUG POINT 3");
+        TestEngine.logErr("Error in: navigator.geolocation.getCurrentPosition");
+    }
+    jsPrint("DEBUG POINT 4");
+}
+
+TestEngine.setTestSuiteName("[WAC2.0][Geolocation]", 30*1000); // 30 seconds
+TestEngine.addTest(true, presenceTest, "[WAC2.0][Geolocation] Geolocation prenence test");
+TestEngine.addTest(true, accessTest, "[WAC2.0][Geolocation] Access test");
+TestEngine.setFinalCallback(function(){ jsPrint("closing window"); window.close(); });
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestMessaging.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestMessaging.js
new file mode 100644 (file)
index 0000000..a0cce73
--- /dev/null
@@ -0,0 +1,1248 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test contact class.
+ *
+ * @author      Lukasz Marek (l.marek@samsung.com)
+ * @version     0.1
+ */
+
+
+var MsgObj = deviceapis.messaging;
+var FsObj = deviceapis.filesystem;
+var destinationPhoneNumbers = ["+48784619935", "+48784619935"];
+var destinationEmails = ["ibisz.krzys@gmail.com"];
+var filename1 = "Attachment1.txt"
+var filename2 = "Attachment2.txt"
+var filename3 = "Attachment3.txt"
+var file1 = null
+var file2 = null
+var file3 = null
+var imageDir = null;
+var currentDate = new Date();
+var defaultBody = "first message%\\ " + currentDate;
+var changedBody = "changed body";
+var INVALID_VALUES_ERR = 22;
+var TYPE_MISMATCH_ERR = 17;
+
+// msg001
+function presenceTest()
+{
+    TestEngine.test("Checking checking", true);
+    TestEngine.test("Checking deviceapis object", deviceapis);
+    TestEngine.test("Checking messaging object", MsgObj);
+    TestEngine.test("Checking filesystem object", FsObj);
+
+    TestEngine.test("Checking type of createMessage", isFunction(MsgObj.createMessage));
+    TestEngine.test("Checking type of sendMessage", isFunction(MsgObj.sendMessage));
+    TestEngine.test("Checking type of findMessages", isFunction(MsgObj.findMessages));
+    TestEngine.test("Checking type of onSMS", isFunction(MsgObj.onSMS));
+    TestEngine.test("Checking type of onMMS", isFunction(MsgObj.onMMS));
+    TestEngine.test("Checking type of onEmail", isFunction(MsgObj.onEmail));
+    TestEngine.test("Checking type of unsubscribe", isFunction(MsgObj.unsubscribe));
+
+    TestEngine.test("Checking type and value of TYPE_SMS", MsgObj.TYPE_SMS === 1);
+    TestEngine.test("Checking type and value of TYPE_MMS", MsgObj.TYPE_MMS === 2);
+    TestEngine.test("Checking type and value of TYPE_EMAIL", MsgObj.TYPE_EMAIL === 3);
+    MsgObj.TYPE_SMS = 66;
+    MsgObj.TYPE_MMS = 66;
+    MsgObj.TYPE_EMAIL = 66;
+    TestEngine.test("Checking read only of TYPE_SMS", MsgObj.TYPE_SMS === 1);
+    TestEngine.test("Checking read only of TYPE_MMS", MsgObj.TYPE_MMS === 2);
+    TestEngine.test("Checking read only of TYPE_EMAIL", MsgObj.TYPE_EMAIL === 3);
+
+    TestEngine.test("Checking type and value of FOLDER_INBOX", MsgObj.FOLDER_INBOX === 1);
+    TestEngine.test("Checking type and value of FOLDER_OUTBOX", MsgObj.FOLDER_OUTBOX === 2);
+    TestEngine.test("Checking type and value of FOLDER_DRAFTS", MsgObj.FOLDER_DRAFTS === 3);
+    TestEngine.test("Checking type and value of FOLDER_SENTBOX", MsgObj.FOLDER_SENTBOX === 4);
+    MsgObj.FOLDER_INBOX = 66;
+    MsgObj.FOLDER_OUTBOX = 66;
+    MsgObj.FOLDER_DRAFTS = 66;
+    MsgObj.FOLDER_SENTBOX = 66;
+    TestEngine.test("Checking type and value of FOLDER_INBOX", MsgObj.FOLDER_INBOX === 1);
+    TestEngine.test("Checking type and value of FOLDER_OUTBOX", MsgObj.FOLDER_OUTBOX === 2);
+    TestEngine.test("Checking type and value of FOLDER_DRAFTS", MsgObj.FOLDER_DRAFTS === 3);
+    TestEngine.test("Checking type and value of FOLDER_SENTBOX", MsgObj.FOLDER_SENTBOX === 4);
+}
+
+// msg002
+function createMessageInvalidParamsTest()
+{
+    TestEngine.catchErrorType("code", INVALID_VALUES_ERR, MsgObj, "createMessage", undefined);
+    TestEngine.catchErrorType("code", INVALID_VALUES_ERR, MsgObj, "createMessage", null);
+    TestEngine.catchErrorType("code", INVALID_VALUES_ERR, MsgObj, "createMessage", "test");
+    TestEngine.catchErrorType("code", INVALID_VALUES_ERR, MsgObj, "createMessage", new Date());
+    TestEngine.catchErrorType("code", INVALID_VALUES_ERR, MsgObj, "createMessage", [6, 6, 6]);
+}
+
+// msg003
+function createMMSTest()
+{
+    createMessageCheck(MsgObj.TYPE_MMS);
+}
+
+// msg004
+function createSMSTest()
+{
+    createMessageCheck(MsgObj.TYPE_SMS);
+}
+
+// msg005
+function createEmailTest()
+{
+    createMessageCheck(MsgObj.TYPE_EMAIL);
+}
+
+function createMessageCheck(type)
+{
+    try {
+        var msg = MsgObj.createMessage(type);
+    } catch (e) {
+        TestEngine.test("Exception error raised", true);
+        return;
+    }
+    TestEngine.test("Exception error not raised", false);
+//    TestEngine.test("message object created", typeof(msg) == 'object');
+//    if (typeof(msg) == 'object') {
+//
+//        var props = new Array();
+//        props.push(new Array('id',null,"999",true,TestEngine.STRING));
+//        props.push(new Array('type',MsgObj.type,999,false,TestEngine.NUMBER));
+//        props.push(new Array('folder',undefined,999,false,undefined));
+//        props.push(new Array('timestamp',null,new Date(2010,12,17),true,TestEngine.DATE));
+//
+//        // email only
+//        if(type === MsgObj.TYPE_EMAIL) {
+//            props.push(new Array('from',null,"maupa@samsung.com",true,TestEngine.STRING));
+//            props.push(new Array('cc',null,null,false));
+//            TestEngine.test("length of cc attribute", msg.cc.length === 0);
+//            props.push(new Array('bcc',null,null,false));
+//            TestEngine.test("length of bcc attribute", msg.bcc.length === 0);
+//            props.push(new Array('priority',null,true,false,TestEngine.BOOL));
+//        }
+//
+//        props.push(new Array('to',null,null,false));
+//        props.push(new Array('body',null,"test",false,TestEngine.STRING));
+//        props.push(new Array('isRead',null,true,false,TestEngine.BOOL));
+//
+//        // MMS and email only
+//        if(type === MsgObj.TYPE_EMAIL || type == MsgObj.TYPE_MMS) {
+//            props.push(new Array('subject',null,"subject",false,TestEngine.STRING));
+//            props.push(new Array('attachments'));
+//            TestEngine.test("length of attachments attribute", msg.attachments.length === 0);
+//        }
+//
+//        props.push(new Array('update',null,null,false,TestEngine.FUNCTION));
+//        TestEngine.testProperties(msg, props);
+//
+//        TestEngine.test("length of to attribute", msg.to.length === 0);
+//    }
+}
+
+// msg006
+function sendMessageInvalidParamsTest()
+{
+    function messageSent() {
+        TestEngine.test("The SMS has been sent", false);
+    }
+    function messageFailed(error) {
+        TestEngine.test("The SMS could not be sent " + error.message, true);
+    }
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage");
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent);
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed);
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, undefined);
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, null);
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, 66);
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, "test");
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, new Date());
+    TestEngine.catchErrorType("code",17, MsgObj, "sendMessage", messageSent, messageFailed, [6, 6, 6]);
+
+    var msg = MsgObj.createMessage(MsgObj.TYPE_SMS);
+    msg.body = "Message sent by test unit sendMessageInvalidParamsTest()";
+    msg.subject = "Subject of message";
+    msg.to = destinationPhoneNumbers;
+    var cbObj = TestEngine.registerCallback("sendMessage", null, messageFailed);
+    MsgObj.sendMessage(null, cbObj.errorCallback, msg);
+}
+
+function sendMMSTestSuccess()
+{
+    TestEngine.test("callback: MMS is sent", true);
+}
+
+function sendMMSTestFail()
+{
+    TestEngine.test("callback: MMS is sent", false);
+}
+
+// msg007
+function sendMMSTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_MMS);
+    if (typeof(msg) == 'object') {
+        TestEngine.test("MMS is created", true);
+        msg.body = "Message sent by test unit sendMMSTest()";
+        msg.subject = "Subject of message";
+        msg.to = destinationPhoneNumbers;
+        //some attachments?
+        var cbObj = TestEngine.registerCallback("sendMMSTest", sendMMSTestSuccess, sendMMSTestFail);
+        MsgObj.sendMessage(cbObj.successCallback, cbObj.errorCallback, msg);
+    }
+    else {
+        TestEngine.test("MMS is created", false);
+    }
+}
+
+function sendSMSTestSuccess()
+{
+    TestEngine.test("callback: SMS is sent", true);
+}
+
+function sendSMSTestFail()
+{
+    TestEngine.test("callback: SMS is sent", false);
+}
+
+// msg008
+function sendSMSTest()
+{
+    var msg1 = MsgObj.createMessage(MsgObj.TYPE_SMS);
+    if (typeof(msg1) == 'object') {
+        TestEngine.test("SMS is created", true);
+
+        msg1.body = "Message 1 sent by test unit sendSMSTest()";
+        msg1.to = destinationPhoneNumbers;
+        var cbObj1 = TestEngine.registerCallback("sendSMSTest1", sendSMSTestSuccess, sendSMSTestFail);
+        MsgObj.sendMessage(cbObj1.successCallback, cbObj1.errorCallback, msg1);
+    }
+    else {
+        TestEngine.test("SMS is created", false);
+    }
+}
+
+function sendEmailTestSuccess()
+{
+    TestEngine.test("callback: Email is sent", true);
+}
+
+function sendEmailTestFail()
+{
+    TestEngine.test("callback: Email is not sent", false);
+}
+
+// msg009
+function sendEmailTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+    if (typeof(msg) == 'object') {
+        TestEngine.test("Email is created", true);
+        msg.body = "Message sent by test unit sendEmailTest()";
+        msg.subject = "[WIDGET SPAM]Subject of message";
+        msg.to = destinationEmails;
+        //some attachments?
+        var cbObj = TestEngine.registerCallback("sendEmailTest", sendEmailTestSuccess, sendEmailTestFail);
+        MsgObj.sendMessage(cbObj.successCallback, cbObj.errorCallback, msg);
+    }
+    else {
+        TestEngine.test("Email is not created", false);
+    }
+}
+
+function findMessageTest(type)
+{
+    var addr1 = "+48123456789";
+    var addr2 = "+48607880564";
+    var addr3 = "+48111111111";
+    var addr4 = "+48999999999";
+    if(type === MsgObj.TYPE_EMAIL) {
+        addr1 = "aaa@bbb.com";
+        addr2 = "bbb@bbb.com";
+        addr3 = "ccc@bbb.com";
+        addr4 = "ddd@bbb.com";
+    }
+
+    var cases = new Array();
+    var currentCase = 0;
+    var newmsg;
+
+    // success callback
+    function successCallback_findMessages(messages)
+    {
+        TestEngine.logOK("SuccessCallback_findMessages enter, messages=" +messages+ ", msg count=" + messages.length);
+        TestEngine.test("Found more than 0 messages", messages.length > 0);
+
+        var matchFound = false;
+
+        // check results
+        for(var i in messages)
+        {
+            // compare types
+            if(messages[i].type === type) {
+                TestEngine.log("Comparing message (" + messages[i].id + ") type " + messages[i].type + " :OK");
+
+                // compare bodies
+                if(messages[i].body.indexOf(defaultBody) === 0) {
+                    TestEngine.log("Comparing message (" + messages[i].id + ") body " + messages[i].body + " :OK");
+                    matchFound = true;
+                    break;
+                }
+                else {
+                    TestEngine.log("Comparing message (" + messages[i].id + ") body " + messages[i].body + " :failed" );
+                }
+            }
+            else {
+                TestEngine.log("Comparing message (" + messages[i].id + ") type " + messages[i].type + " :failed" );
+            }
+        }
+
+        TestEngine.test("Match found" , matchFound);
+
+        currentCase++;
+        processNextCase();
+    }
+
+    // error callback
+    function errorCallback_findMessages(result)
+    {
+        TestEngine.test("errorCallback_findMessages enter, result.code=" + result.code, false);
+
+        currentCase++;
+        processNextCase();
+    }
+
+    // send success callback
+    function sendSucceeded() {
+        TestEngine.test("Test message successfully sent", true);
+
+        var msg;
+
+        //set up body filter
+        msg = { body:"first messa%", description:"Filter by body" };
+        cases.push(msg);
+
+        //set up subject filter
+        if(type != MsgObj.TYPE_SMS) {
+            msg = { subject:"%meaningless%", description:"Filter by subject" };
+            cases.push(msg);
+        }
+
+        //set up destination address filter
+        msg = { to:[addr1], description:"Filter by to" };
+        cases.push(msg);
+
+        //set up isRead filter
+        msg = { isRead:false, description:"Filter by isRead" };
+        cases.push(msg);
+
+        if (type === MsgObj.TYPE_EMAIL) {
+            //set up messagePriority filter
+            msg = { messagePriority:true, description:"Filter by messagePriority" };
+            cases.push(msg);
+
+            //set up cc filter
+            msg = { cc:[addr3], description:"Filter by cc" };
+            cases.push(msg);
+
+            //set up bcc filter
+            msg = { bcc:[addr4], description:"Filter by bcc" };
+            cases.push(msg);
+
+            //set up id filter
+            msg = { id:newmsg.id, description:"Filter by id" };
+            cases.push(msg);
+        }
+
+        //set up time filter
+        var start = new Date(2009,01);
+        var end = new Date(2015,01);
+        msg = { startTimestamp:start, endTimestamp:end, description:"Filter by dates" };
+        cases.push(msg);
+
+        //set up folder filter
+        msg = { folder:[MsgObj.FOLDER_SENTBOX], description:"Filter by folder" };
+        cases.push(msg);
+
+        //set up from filter
+        msg = { from:newmsg.from, description:"Filter by from" };
+        cases.push(msg);
+
+        //set up complex filter
+        msg = { body:"first messa%",
+                to:[addr1],
+                id:newmsg.id,
+                startTimestamp:start,
+                endTimestamp:end,
+                folder:[MsgObj.FOLDER_SENTBOX],
+                type:[type],
+                from:newmsg.from,
+                description:"complex filter"
+                };
+        if (type != MsgObj.TYPE_EMAIL) {
+            delete msg.id;
+        }
+
+        cases.push(msg);
+
+        // % (0 or more) and escape character. \\% - escaped '%', \\ - '\'
+        msg = { body:"%first %sage\\%\\ %", description:"Filter by body (% and escapes)" }
+        cases.push(msg);
+
+        // % (0 or more) in string array
+        if(type === MsgObj.TYPE_EMAIL) {
+            msg = { to:["%@bbb.%","%aa%"], description:"Filter by to (using %)" }     // EMAIL
+        }
+        else {
+            msg = { to:["%1234%","%45678%"], description:"Filter by to (using %)" }   // MMS & MMS
+        }
+        cases.push(msg);
+
+        processNextCase();
+    }
+
+    // send failure callback
+    function sendFailed() {
+        TestEngine.test("Test message sending failed", false);
+    }
+
+    // helper function
+    function processNextCase() {
+        if(currentCase < cases.length) {
+            TestEngine.log("");
+            TestEngine.log("Processing case " + currentCase);
+            TestEngine.log(cases[currentCase].description);
+            delete cases[currentCase].description;
+            var cObj = TestEngine.registerCallback("findMessages", successCallback_findMessages, errorCallback_findMessages)
+            MsgObj.findMessages(cObj.successCallback, cObj.errorCallback, cases[currentCase])
+        }
+    }
+
+    try {
+        //create message to be found
+        newmsg = MsgObj.createMessage(type);
+        newmsg.body = defaultBody;
+        newmsg.to = [addr1,addr2];
+        if(type === MsgObj.TYPE_EMAIL) {
+            newmsg.cc = [addr3];
+            newmsg.bcc = [addr4];
+            newmsg.priority = true;
+        }
+        if(type != MsgObj.SMS) {
+            newmsg.subject = "some meaningless subject";
+        }
+        var cb = TestEngine.registerCallback("sendMessage",sendSucceeded,sendFailed);
+        MsgObj.sendMessage(cb.successCallback,cb.errorCallback,newmsg);
+
+    } catch(e) {
+        TestEngine.logErr("findMessages exception: " + e.message);
+    }
+}
+
+function findNoMessageTest(type)
+{
+    var addr1 = "+48123456789";
+    var addr2 = "+48607880564";
+    var addr3 = "+48111111111";
+    var addr4 = "+48999999999";
+    if(type === MsgObj.TYPE_EMAIL)
+    {
+        addr1 = "aaa@bbb.com";
+        addr2 = "bbb@bbb.com";
+        addr3 = "ccc@bbb.com";
+        addr4 = "ddd@bbb.com";
+    }
+
+    var cases = new Array();
+    var currentCase = 0;
+    var newmsg;
+
+    // success callback
+    function successCallback_findMessages(messages)
+    {
+        TestEngine.logOK("successCallback_findMessages enter, messages=" +messages+ ", msg count=" + messages.length);
+        TestEngine.test("No messages should be found", messages.length == 0);
+
+        currentCase++;
+        processNextCase();
+    }
+
+    // error callback
+    function errorCallback_findMessages(result)
+    {
+        TestEngine.test("errorCallback_findMessages enter, result.code=" + result.code, false);
+
+        currentCase++;
+        processNextCase();
+    }
+
+    // send success callback
+    function sendSucceeded() {
+        TestEngine.test("Test message successfully sent", true);
+
+        //set up body filter
+        msg = { body:"first messaa%", id:newmsg.id };
+        cases.push(msg);
+
+        //set up subject filter
+        msg = { subject:"%meaningleess%", id:newmsg.id };
+        cases.push(msg);
+
+        //set up destination address filter
+        msg = { to:[addr3], id:newmsg.id };
+        cases.push(msg);
+
+        //set up isRead filter
+        msg = { isRead:true, id:newmsg.id };
+        cases.push(msg);
+
+        //set up messagePriority filter
+        msg = { messagePriority:false, id:newmsg.id };
+        cases.push(msg);
+
+        //set up id filter
+        msg = { id:newmsg.id + "0000" };
+        cases.push(msg);
+
+        //set up time filter
+        var start = new Date(2008,01);
+        var end = new Date(2010,01);
+        msg = { endTimestamp:end, id:newmsg.id };
+        cases.push(msg);
+
+        //set up folder filter
+        msg = { folder:[MsgObj.FOLDER_INBOX], id:newmsg.id };
+        cases.push(msg);
+
+        //set up from filter
+        msg = { from:"aaa@aaa.com", id:newmsg.id };
+        cases.push(msg);
+
+        //set up cc filter
+        msg = { cc:[addr1], id:newmsg.id };
+        cases.push(msg);
+
+        //set up bcc filter
+        msg = { bcc:[addr1], id:newmsg.id };
+        cases.push(msg);
+
+        // % (0 or more) and escape character
+        msg = { body:"%first mess%sage\%", id:newmsg.id }
+        cases.push(msg);
+
+        // % (0 or more) in string array
+        if(type === MsgObj.TYPE_EMAIL) {
+            msg = { to:["%c@bbb.%","%aa%"], id:newmsg.id }     // EMAIL
+        }
+        else {
+            msg = { to:["%12354%","%45678%"], id:newmsg.id }   // MMS & SMS
+        }
+        cases.push(msg);
+
+        processNextCase();
+    }
+
+    // send failure callback
+    function sendFailed() {
+        TestEngine.test("Test message sending failed", false);
+    }
+
+    // helper function
+    function processNextCase() {
+        if(currentCase < cases.length) {
+            TestEngine.log("");
+            TestEngine.log("Processing case " + currentCase);
+            var cObj = TestEngine.registerCallback("findMessages", successCallback_findMessages, errorCallback_findMessages)
+            MsgObj.findMessages(cObj.successCallback, cObj.errorCallback, cases[currentCase])
+        }
+    }
+
+    try {
+        //create message not to be found
+        newmsg = MsgObj.createMessage(type);
+        newmsg.body = "first message"
+        newmsg.to = [addr1,addr2];
+        if(type === MsgObj.TYPE_EMAIL) {
+            newmsg.cc = [addr3];
+            newmsg.bcc = [addr4];
+            newmsg.priority = true;
+        }
+        if(type != MsgObj.SMS) {
+            newmsg.subject = "some meaningless subject";
+        }
+        var cb = TestEngine.registerCallback("sendMessage",sendSucceeded,sendFailed);
+        MsgObj.sendMessage(cb.successCallback,cb.errorCallback,newmsg);
+
+    } catch(e) {
+        TestEngine.logErr("findMessages exception: " + e.message);
+    }
+}
+
+// msg013
+function findEmailTest()
+{
+    findMessageTest(MsgObj.TYPE_EMAIL)
+}
+
+// msg014
+function findSMSTest()
+{
+    findMessageTest(MsgObj.TYPE_SMS)
+}
+
+// msg015
+function findMMSTest()
+{
+    findMessageTest(MsgObj.TYPE_MMS)
+}
+
+// msg016
+function findNoEmailTest()
+{
+    findNoMessageTest(MsgObj.TYPE_EMAIL)
+}
+
+// msg017
+function findNoSMSTest()
+{
+    findNoMessageTest(MsgObj.TYPE_SMS)
+}
+
+// msg018
+function findNoMMSTest()
+{
+    findNoMessageTest(MsgObj.TYPE_MMS)
+}
+
+// msg019
+function findMessageInvalidParamsTest()
+{
+    function messageFound() {
+        TestEngine.test("The message has been found", false);
+    }
+    function messageFailed(error) {
+        TestEngine.test("The message could not be found " + error.message, true);
+    }
+
+    var cb = TestEngine.registerCallback("findMessages", null, messageFailed);
+    MsgObj.findMessages(null, cb.errorCallback);
+
+    var filter = { type:[MsgObj.TYPE_SMS], body:"aaa" };
+    var cb = TestEngine.registerCallback("findMessages", null, messageFailed);
+    MsgObj.findMessages(null, cb.errorCallback, filter);
+}
+
+// msg020
+function unsubscribeInvalidTest()
+{
+    invalidUnsubscribeCheck();
+
+    // If the subscriptionHandler argument does not correspond to a valid subscription, the method should return without any further action.
+    try
+    {
+        MsgObj.unsubscribe(123);
+        TestEngine.test("No error thrown from: messaging.unsubscribe", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+function invalidUnsubscribeCheck()
+{
+    TestEngine.catchErrorType("code",17, MsgObj, "unsubscribe");
+}
+
+// msg021
+function onSMSInvalidTest()
+{
+    onIncomingMessageInvalidCheck("onSMS");
+}
+
+// msg022
+function onMMSInvalidTest()
+{
+    onIncomingMessageInvalidCheck("onMMS");
+}
+
+// msg023
+function onEmailInvalidTest()
+{
+    onIncomingMessageInvalidCheck("onEmail");
+}
+
+function onIncomingMessageInvalidCheck(func)
+{
+    // bad values
+    TestEngine.catchErrorType("code",17, MsgObj, func);
+    TestEngine.catchErrorType("code",17, MsgObj, func, null);
+    TestEngine.catchErrorType("code",17, MsgObj, func, undefined);
+    TestEngine.catchErrorType("code",17, MsgObj, func, -666);
+    TestEngine.catchErrorType("code",17, MsgObj, func, new Date());
+    TestEngine.catchErrorType("code",17, MsgObj, func, [6, 6, 6]);
+}
+
+// msg024
+function onSMSTest()
+{
+    onIncomingMessageCheck("onSMS");
+}
+
+// msg025
+function onMMSTest()
+{
+    onIncomingMessageCheck("onMMS");
+}
+
+// msg026
+function onEmailTest()
+{
+    onIncomingMessageCheck("onEmail");
+}
+
+function incomingMsgCb(msg)
+{
+    // empty
+}
+
+function onIncomingMessageCheck(func)
+{
+    try
+    {
+        var handler = MsgObj[func](incomingMsgCb);
+        TestEngine.test("No error thrown from: messaging." + func + " (1)", true);
+        var handler2 = MsgObj[func](incomingMsgCb);
+        TestEngine.test("No error thrown from: messaging." + func + " (2)", true);
+
+        // is still should be impossible to unsubscribe with invalid args
+        invalidUnsubscribeCheck();
+
+        TestEngine.test("Checking type of returned handle (1)", isNumber(handler));
+        TestEngine.test("Checking value of returned handle (1)", handler >= 0);
+        TestEngine.test("Checking type of returned handle (2)", isNumber(handler2));
+        TestEngine.test("Checking value of returned handle (2)", handler2 >= 0);
+        TestEngine.test("Comparing values of returned handles", handler != handler2);
+
+        MsgObj.unsubscribe(handler);
+        TestEngine.test("No error thrown from: messaging.unsubscribe (1)", true);
+        MsgObj.unsubscribe(handler2);
+        TestEngine.test("No error thrown from: messaging.unsubscribe (2)", true);
+        MsgObj.unsubscribe(handler);
+        TestEngine.test("No error thrown from: messaging.unsubscribe after unsubscribing (1)", true);
+        MsgObj.unsubscribe(handler2);
+        TestEngine.test("No error thrown from: messaging.unsubscribe after unsubscribing (2)", true);
+    }
+    catch(err)
+    {
+        TestEngine.logException(err.message);
+    }
+}
+
+// msg027
+function attachmentPrecondition()
+{
+    // resolve image directory
+    function on_resolve_success(dir) {
+        imageDir = dir;
+        TestEngine.test("Attachment precondition passed",true);
+
+        // create attachment file
+        try {
+            imageDir.createFile(filename1);
+            imageDir.createFile(filename2);
+            imageDir.createFile(filename3);
+        }
+        catch (error) {
+            TestEngine.test("File already exists. Ignoring",error.code == 100); // IO_ERR
+        }
+
+        file1 = imageDir.resolve(filename1);
+        TestEngine.test("checking file1", file1 != null && file1 != undefined)
+
+        file2 = imageDir.resolve(filename2);
+        TestEngine.test("checking file2", file2 != null && file2 != undefined)
+
+        file3 = imageDir.resolve(filename3);
+        TestEngine.test("checking file3", file3 != null && file3 != undefined)
+    }
+    function on_resolve_error() {
+        TestEngine.test("Attachment precondition failed",false);
+    }
+    var cb = TestEngine.registerCallback("resolve", on_resolve_success, on_resolve_error);
+       FsObj.resolve(cb.successCallback, cb.errorCallback, "music");
+}
+
+// msg028
+function attachmentSMSTest()
+{
+    // for sms attachments MUST be ignored
+    var msg = MsgObj.createMessage(MsgObj.TYPE_SMS);
+    msg.body = "body";
+    msg.to = destinationPhoneNumbers;
+
+    // check attachments array
+    var att = new Array();
+    att[0] = file1;
+    msg.attachments = att;
+
+    // check sending attachments
+    function sendSuccess() {
+        TestEngine.test("Message sent successfully",true);
+    }
+
+    function sendFail() {
+        TestEngine.test("Message sending failed",false);
+    }
+
+    var cbObj = TestEngine.registerCallback("sendMessage", sendSuccess, sendFail);
+    MsgObj.sendMessage(cbObj.successCallback, cbObj.errorCallback, msg);
+}
+
+// msg029
+function attachmentMMSTest()
+{
+    attachmentCheck(MsgObj.TYPE_MMS);
+}
+
+// msg030
+function attachmentEmailTest()
+{
+    attachmentCheck(MsgObj.TYPE_EMAIL);
+}
+
+function attachmentCheck(type)
+{
+    var msg = MsgObj.createMessage(type);
+    msg.subject = "subject";
+    msg.body = "body";
+    msg.to = destinationPhoneNumbers;
+    if(type === MsgObj.TYPE_EMAIL) {
+        msg.to = destinationEmails;
+    }
+
+    msg.attachments = new Array(file1,file2,file3);
+
+    // check sending attachments
+    function sendSuccess() {
+        TestEngine.test("Message sent successfully",true);
+    }
+
+    function sendFail() {
+        TestEngine.test("Message sending failed",false);
+    }
+
+    var cbObj = TestEngine.registerCallback("sendMessage", sendSuccess, sendFail);
+    MsgObj.sendMessage(cbObj.successCallback, cbObj.errorCallback, msg);
+}
+
+// msg031
+function updateTestSMS()
+{
+    updateCheck(MsgObj.TYPE_SMS);
+}
+
+// msg032
+function updateTestMMS()
+{
+    updateCheck(MsgObj.TYPE_MMS);
+}
+
+// msg033
+function updateTestEmail()
+{
+    updateCheck(MsgObj.TYPE_EMAIL);
+}
+
+function updateCheck(type)
+{
+    TestEngine.log("Checking update function for message type: " + type);
+    var read;
+    var body;
+    var msg;
+
+    var addr1 = "+48123456789";
+    if(type === MsgObj.TYPE_EMAIL) {
+        addr1 = "aaa@bbb.com";
+    }
+
+    ///////////////  3   //////////////////
+    function updateSuccess2(msg) {
+        TestEngine.test("updateSuccess (2)" , true);
+
+        ///////////////  4   //////////////////
+        function findChangedSuccess(messages) {
+            TestEngine.test("findChangedSuccess",true);
+
+            // and compare it
+            TestEngine.test("Comparing 'body' attribute", changedBody != messages[0].body); // should not be changed
+
+            // invalid arguments
+            TestEngine.catchErrorType("code",17, messages[0], "update");
+            TestEngine.catchErrorType("code",17, messages[0], "update", 666, updateFailure);
+        }
+
+        function findChangesFailure() {
+            TestEngine.test("findChangesFailure",false);
+        }
+
+        var filter = { id:msg.id };
+        var cb6 = TestEngine.registerCallback("findMessages2", findChangedSuccess, findChangesFailure)
+        MsgObj.findMessages(cb6.successCallback, cb6.errorCallback, filter)
+    }
+
+    ///////////////  2   //////////////////
+    // find callbacks
+    function findSuccess(messages) {
+        TestEngine.logOK("findSuccess, messages=" +messages+ ", msg count=" + messages.length);
+        TestEngine.test("found messages", messages.length > 0);
+
+        // update isRead attribute (should pass)
+        read = messages[0].isRead;
+        messages[0].isRead = !read;
+        messages[0].body = changedBody;
+        var cb4 = TestEngine.registerCallback("update2", updateSuccess2, updateFailure);
+        messages[0].update(cb4.successCallback, cb4.errorCallback);
+    }
+
+    function findFailure(result) {
+        TestEngine.test("findFailure, result.code=" + result.code, false);
+    }
+
+    function updateFailure() {
+        TestEngine.test("updateFailure",false);
+    }
+
+
+    ///////////////  1   //////////////////
+    // send callbacks
+    function sendSuccess() {
+        TestEngine.test("sendSuccess" , true);
+
+        var filter = { body:"first message%",folder:[MsgObj.FOLDER_OUTBOX,MsgObj.FOLDER_SENTBOX]  };
+
+        var cb3 = TestEngine.registerCallback("findMessages", findSuccess, findFailure)
+        MsgObj.findMessages(cb3.successCallback, cb3.errorCallback, filter)
+    }
+
+    function sendFailure() {
+        TestEngine.test("sendFailure" , false);
+    }
+
+    // update created message
+    msg = MsgObj.createMessage(type);
+    msg.body = "first message"
+    msg.to = [addr1];
+    msg.isRead = true;
+    var cb = TestEngine.registerCallback("sendMessage", sendSuccess, sendFailure);
+    MsgObj.sendMessage(cb.successCallback, cb.errorCallback, msg);
+}
+
+// msg034
+function cancelingSendingTest()
+{
+    var canceled = false;
+    function errorCallback() {
+        TestEngine.test("sending error callback", false);
+    }
+    function successCallback() {
+        TestEngine.test("sending success callback", !canceled);
+    }
+
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    TestEngine.test("Checking message ",msg != undefined);
+
+    if(msg != undefined) {
+        msg.to = destinationEmails;
+        msg.body = "body";
+
+        var cObj = TestEngine.registerCallback("send", successCallback, errorCallback)
+        var pendingOperation = MsgObj.sendMessage(cObj.successCallback, cObj.errorCallback, msg);
+
+        canceled = pendingOperation.cancel();
+        TestEngine.test("Canceling MsgObj.sendMessage. Cancelled: " + canceled, true);
+        if (canceled) {
+            TestEngine.callbackMutex--;
+        }
+    }
+}
+
+// msg035
+function cancelingFindingTest()
+{
+    var canceled = false;
+    function errorCallback() {
+        TestEngine.test("find error callback", false);
+    }
+    function successCallback() {
+        TestEngine.test("find success callback", !canceled);
+    }
+    var cObj = TestEngine.registerCallback("find", successCallback, errorCallback)
+
+    var msg = { body:"body" };
+    var pendingOperation = MsgObj.findMessages(cObj.successCallback, cObj.errorCallback, msg);
+
+    canceled = pendingOperation.cancel();
+    TestEngine.test("Canceling MsgObj.findMessage. Cancelled: " + canceled, true);
+    if (canceled) {
+        TestEngine.callbackMutex--;
+    }
+}
+
+// msg036
+function cancelingUpdateTest()
+{
+    function errorCallback(err) {
+        TestEngine.test("sending error callback [" + err.code + "]", false);
+    }
+
+    function successCallback() {
+        TestEngine.test("sending success callback", true);
+
+        var canceled = false;
+
+        function updateSuccess(msg)
+        {
+            TestEngine.test("update() canceled = " + canceled, !canceled);
+        }
+
+        function updateError(err)
+        {
+            TestEngine.test("update() [" + err.code + "]", false);
+        }
+
+        var cObj = TestEngine.registerCallback("update", updateSuccess, updateError);
+        var pendingOperation = msg.update(cObj.successCallback, cObj.errorCallback);
+        if (pendingOperation != null)
+        {
+            canceled = pendingOperation.cancel();
+            TestEngine.test("Canceling Message.update. Cancelled: " + canceled, true);
+            if (canceled) {
+                TestEngine.callbackMutex--;
+            }
+        }
+    }
+
+    // create message
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+    TestEngine.test("Checking message ", msg != undefined);
+
+    if (msg != undefined) {
+        msg.body = "first message"
+        msg.to = ["wrt.spam@samsung.com"];
+        msg.isRead = true;
+
+        var cObj = TestEngine.registerCallback("send", successCallback, errorCallback);
+        MsgObj.sendMessage(cObj.successCallback, cObj.errorCallback, msg);
+    }
+}
+
+function compareAttachments(att1,att2)
+{
+    if(att1 === undefined && att2 === undefined) {
+        TestEngine.test("Both attachments are undefined", true);
+        return;
+    }
+    if(att1 === undefined || att2 === undefined) {
+        TestEngine.test("Attachment is undefined", false);
+        return;
+    }
+    TestEngine.test("Comparing attachments " + att1.fullPath + " with " + att2.fullPath, att1.fullPath == att2.fullPath);
+}
+
+function checkAttachmentsLength(att,len)
+{
+    TestEngine.test("Checking attachments length. Expected:" + len + " supplied:" + att.length, len === att.length);
+}
+
+// msg037
+function attachmentsIndexTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check indexes
+    msg.attachments[0] = file1;
+    checkAttachmentsLength(msg.attachments,1);
+    compareAttachments(msg.attachments[0],file1);
+    try
+    {
+        msg.attachments[2] = file2;
+    }
+    catch (e)
+    {
+        TestEngine.test("ERR: Injecting sparse (undefined) items.", (e.code == TYPE_MISMATCH_ERR));
+    }
+}
+
+// msg038
+function attachmentsConcatTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check concat
+    msg.attachments = new Array(file1);
+    var att = new Array(file2,file1);
+    var att2 = msg.attachments.concat(att);
+    checkAttachmentsLength(msg.attachments,1);
+    checkAttachmentsLength(att2,3);
+    compareAttachments(att2[0],file1);
+    compareAttachments(att2[1],file2);
+    compareAttachments(att2[2],file1);
+}
+
+// msg039
+function attachmentsPopTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check pop
+    msg.attachments = new Array(file1,file2);
+    var last = msg.attachments.pop();
+    checkAttachmentsLength(msg.attachments,1);
+    compareAttachments(last,file2);
+    compareAttachments(msg.attachments[0],file1);
+}
+
+// msg040
+function attachmentsPushTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check push
+    msg.attachments = new Array(file1);
+    var len = msg.attachments.push(file2);
+    checkAttachmentsLength(msg.attachments,2);
+    checkAttachmentsLength(msg.attachments,len);
+    compareAttachments(msg.attachments[1],file2);
+}
+
+// msg041
+function attachmentsReverseTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check reverse
+    msg.attachments = new Array(file1,file2);
+    msg.attachments.reverse();
+    compareAttachments(msg.attachments[1],file1);
+    compareAttachments(msg.attachments[0],file2);
+    checkAttachmentsLength(msg.attachments,2);
+}
+
+// msg042
+function attachmentsShiftTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check shift
+    msg.attachments = new Array(file1,file2);
+    var first = msg.attachments.shift();
+    checkAttachmentsLength(msg.attachments,1);
+    compareAttachments(first,file1);
+    compareAttachments(msg.attachments[0],file2);
+}
+
+// msg043
+function attachmentsSliceTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check slice
+    msg.attachments = new Array(file1,file2,file3,file1);
+    var sliced = msg.attachments.slice(1,3);
+    checkAttachmentsLength(sliced,2);
+    compareAttachments(sliced[0],file2);
+    compareAttachments(sliced[1],file3);
+}
+
+// msg044
+function attachmentsSpliceTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    //check splice
+    msg.attachments = new Array(file1,file2,file3,file2);
+    var spliced = msg.attachments.splice(1,10,file3,file2);
+    checkAttachmentsLength(spliced,3);
+    compareAttachments(spliced[0],file2);
+    compareAttachments(spliced[1],file3);
+    compareAttachments(spliced[2],file2);
+    checkAttachmentsLength(msg.attachments,3);
+    compareAttachments(msg.attachments[0],file1);
+    compareAttachments(msg.attachments[1],file3);
+    compareAttachments(msg.attachments[2],file2);
+}
+
+// msg045
+function attachmentsUnshiftTest()
+{
+    var msg = MsgObj.createMessage(MsgObj.TYPE_EMAIL);
+
+    // check unshift
+    msg.attachments = new Array(file1,file2,file3);
+    var len = msg.attachments.unshift(file2);
+    checkAttachmentsLength(msg.attachments,4);
+    checkAttachmentsLength(msg.attachments,len);
+    compareAttachments(msg.attachments[0],file2);
+    compareAttachments(msg.attachments[1],file1);
+}
+
+
+//=============================================================================
+
+TestEngine.setTestSuiteName("[WAC2.0][Messaging]", 2*60*1000); //2min time out for callbacks
+//TestEngine.addTest(true, presenceTest, "[WAC2.0][Messaging] messaging functions presence test");
+//TestEngine.addTest(true, createMMSTest, "[WAC2.0][Messaging] create MMS test");
+TestEngine.addTest(true, createSMSTest, "[WAC2.0][Messaging] create SMS test");
+//TestEngine.addTest(true, createEmailTest, "[WAC2.0][Messaging] create email test");
+//TestEngine.addTest(true, createMessageInvalidParamsTest, "[WAC2.0][Messaging] create message function with invalid params test");
+//TestEngine.addTest(true, sendMMSTest, "[WAC2.0][Messaging] send MMS test");
+//TestEngine.addTest(true, sendSMSTest, "[WAC2.0][Messaging] send SMS test");
+//TestEngine.addTest(true, sendEmailTest, "[WAC2.0][Messaging] send Email test");
+//TestEngine.addTest(true, sendMessageInvalidParamsTest, "[WAC2.0][Messaging] send message function with invalid params test");
+//TestEngine.addTest(true, findNoEmailTest, "[WAC2.0][Messaging] find no EMail test");
+//TestEngine.addTest(true, findNoSMSTest, "[WAC2.0][Messaging] find no SMS test");
+//TestEngine.addTest(true, findNoMMSTest, "[WAC2.0][Messaging] find no MMS test");
+//TestEngine.addTest(true, findEmailTest, "[WAC2.0][Messaging] find EMail test");
+//TestEngine.addTest(true, findSMSTest, "[WAC2.0][Messaging] find SMS test");
+//TestEngine.addTest(true, findMMSTest, "[WAC2.0][Messaging] find MMS test");
+//TestEngine.addTest(true, findMessageInvalidParamsTest, "[WAC2.0][Messaging] find message function invalid params test");
+//TestEngine.addTest(true, unsubscribeInvalidTest, "[WAC2.0][Messaging] unsubscribe function with invalid args test");
+//TestEngine.addTest(true, onSMSInvalidTest, "[WAC2.0][Messaging] onSMS function test with invalid values");
+//TestEngine.addTest(true, onMMSInvalidTest, "[WAC2.0][Messaging] onMMS function test with invalid values");
+//TestEngine.addTest(true, onEmailInvalidTest, "[WAC2.0][Messaging] onEmail function test with invalid values");
+//TestEngine.addTest(true, onSMSTest, "[WAC2.0][Messaging] onSMS function test");
+//TestEngine.addTest(true, onMMSTest, "[WAC2.0][Messaging] onMMS function test");
+//TestEngine.addTest(true, onEmailTest, "[WAC2.0][Messaging] onEmail function test");
+//TestEngine.addTest(true, attachmentPrecondition, "[WAC2.0][Messaging] attachment tests precondition");
+//TestEngine.addTest(true, attachmentsIndexTest, "[WAC2.0][Messaging] attachment index tests");
+//TestEngine.addTest(true, attachmentsConcatTest, "[WAC2.0][Messaging] attachment concat tests");
+//TestEngine.addTest(true, attachmentsPopTest, "[WAC2.0][Messaging] attachment pop tests");
+//TestEngine.addTest(true, attachmentsPushTest, "[WAC2.0][Messaging] attachment push tests");
+//TestEngine.addTest(true, attachmentsReverseTest, "[WAC2.0][Messaging] attachment reverse tests");
+//TestEngine.addTest(true, attachmentsShiftTest, "[WAC2.0][Messaging] attachment shift tests");
+//TestEngine.addTest(true, attachmentsSliceTest, "[WAC2.0][Messaging] attachment slice tests");
+//TestEngine.addTest(true, attachmentsSpliceTest, "[WAC2.0][Messaging] attachment splice tests");
+//TestEngine.addTest(true, attachmentsUnshiftTest, "[WAC2.0][Messaging] attachment unshift tests");
+//TestEngine.addTest(true, attachmentSMSTest, "[WAC2.0][Messaging] SMS attachment test");
+//TestEngine.addTest(true, attachmentMMSTest, "[WAC2.0][Messaging] MMS attachment test");
+//TestEngine.addTest(true, attachmentEmailTest, "[WAC2.0][Messaging] Email attachment test");
+//TestEngine.addTest(true, updateTestSMS, "[WAC2.0][Messaging] Sms update test");
+//TestEngine.addTest(true, updateTestMMS, "[WAC2.0][Messaging] Mms update test");
+//TestEngine.addTest(true, updateTestEmail, "[WAC2.0][Messaging] Email update test");
+//TestEngine.addTest(true, cancelingSendingTest, "[WAC2.0][Messaging] Canceling sendMessage test");
+//TestEngine.addTest(true, cancelingFindingTest, "[WAC2.0][Messaging] Canceling findMessage test");
+//TestEngine.addTest(true, cancelingUpdateTest, "[WAC2.0][Messaging] Canceling message update test");
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestOrientation.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestOrientation.js
new file mode 100644 (file)
index 0000000..ab37023
--- /dev/null
@@ -0,0 +1,194 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test Orientation class.
+ *
+ * @author      xiangguo.qi (xiangguo.qi @samsung.com)
+ * @version     0.1
+ */
+
+
+var OrientationObj = deviceapis.orientation;
+var OrientationWatchID = "";
+
+// Orientation001
+function presenceTest()
+{
+    TestEngine.test("Checking checking", true);
+    TestEngine.test("Checking deviceapis object", deviceapis);
+    TestEngine.test("Checking Orientation object", OrientationObj);
+
+    TestEngine.test("Checking type of getCurrentOrientation", isFunction(OrientationObj.getCurrentOrientation));
+    TestEngine.test("Checking type of watchOrientation", isFunction(OrientationObj.watchOrientation));
+    TestEngine.test("Checking type of clearWatch", isFunction(OrientationObj.clearWatch));
+}
+
+function getSuccess(orientation)
+{
+    TestEngine.test("get current orientation", true);
+    TestEngine.test("orientation.alpha", isNumber(orientation.alpha));
+    TestEngine.test("orientation.beta", isNumber(orientation.beta));
+    TestEngine.test("orientation.gamma", isNumber(orientation.gamma));
+}
+
+function getFail()
+{
+    TestEngine.test("get current orientation", false);
+}
+
+
+function acceptError(){
+    TestEngine.test("Error as exptected", true);
+}
+
+function rejectSuccess(){
+    TestEngine.test("Success - error expected", false);
+}
+
+//Orientation002
+function getCurrentOrientationValidParameters()
+{
+    var cbObj = TestEngine.registerCallback("getCurrentOrientation", rejectSuccess, acceptError, 3);
+    try {
+        OrientationObj.getCurrentOrientation(cbObj.successCallback, cbObj.errorCallback);
+        TestEngine.test("exception not thrown", true);
+    } catch(e) {
+        TestEngine.logErr("Exception should not be thrown" + e);
+    }
+//    try {
+//        OrientationObj.getCurrentOrientation(cbObj.successCallback);
+//        TestEngine.test("exception not thrown", true);
+//    } catch(e) {
+//        TestEngine.logErr("Exception should not be thrown" + e);
+//    }
+//    try {
+//        OrientationObj.getCurrentOrientation(cbObj.successCallback, undefined);
+//        TestEngine.test("exception not thrown", true);
+//    } catch(e) {
+//        TestEngine.logErr("Exception should not be thrown" + e);
+//    }
+}
+
+// Orientation003
+function getCurrentOrientationInvalidParamsTest()
+{
+    TestEngine.catchErrorType("code",17, OrientationObj, "getCurrentOrientation", 1234, undefined);
+    TestEngine.catchErrorType("code",17, OrientationObj, "getCurrentOrientation", "test");
+    TestEngine.catchErrorType("code",17, OrientationObj, "getCurrentOrientation", new Date());
+    TestEngine.catchErrorType("code",17, OrientationObj, "getCurrentOrientation", [6, 6, 6]);
+}
+
+
+function successFail()
+{
+    TestEngine.test("Correctly onError called", true);
+}
+
+// Orientation004
+function getCurrentOrientationCheckErrorCallback()
+{
+    var failObj = TestEngine.registerCallback("getCurrentOrientation", getSuccess, successFail);
+    try {
+        OrientationObj.getCurrentOrientation(undefined, failObj.errorCallback);
+    } catch(e) {
+        TestEngine.logErr("Exception should not be thrown" + e);
+    }
+    try {
+        OrientationObj.getCurrentOrientation(1234, failObj.errorCallback);
+        TestEngine.logErr("Exception should be thrown");
+    } catch(e) {
+        TestEngine.logOK("Exception thrown" + e);
+    }
+}
+
+
+// Orientation005
+function watchOrientationInvalidParamsTest()
+{
+    TestEngine.catchErrorType("code",17, OrientationObj, "watchOrientation", "test");
+    TestEngine.catchErrorType("code",17, OrientationObj, "watchOrientation", new Date());
+    TestEngine.catchErrorType("code",17, OrientationObj, "watchOrientation", [6, 6, 6]);
+}
+
+// Orientation006
+function watchOrientationCheck()
+{
+    function watchSuccess(orientation)
+    {
+        OrientationObj.clearWatch(OrientationWatchID);
+        TestEngine.test("watch orientation",true);
+        TestEngine.test("orientation.alpha", isNumber(orientation.alpha));
+        TestEngine.test("orientation.beta", isNumber(orientation.beta));
+        TestEngine.test("orientation.gamma", isNumber(orientation.gamma));
+    }
+
+    function watchFail()
+    {
+        TestEngine.test("watch orientation",false);
+    }
+
+    var cbObj = TestEngine.registerCallback("watchOrientation", watchSuccess, watchFail);
+    try {
+        OrientationWatchID = OrientationObj.watchOrientation(cbObj.successCallback, cbObj.errorCallback, {
+            minNotificationInterval:20
+            });
+        TestEngine.logOK("No exception thrown");
+    } catch (e) {
+        TestEngine.logErr("Exception should not be thrown" + e.toString());
+    }
+}
+
+// Orientation007
+function clearWatchTest()
+{
+    try
+    {
+        OrientationObj.clearWatch(OrientationWatchID);
+        TestEngine.logOK("clearWatch OK");
+    }
+    catch (error) {
+        TestEngine.logErr("clearWatch Error");
+    }
+    try
+    {
+        OrientationObj.clearWatch(undefined);
+        TestEngine.logOK("clearWatch OK");
+    }
+    catch (error) {
+        TestEngine.logErr("clearWatch Error");
+    }
+    try
+    {
+        OrientationObj.clearWatch(null);
+        TestEngine.logOK("clearWatch OK");
+    }
+    catch (error) {
+        TestEngine.logErr("clearWatch Error");
+    }
+}
+
+
+//=============================================================================
+TestEngine.setTestSuiteName("[WAC2.0][Orientation]", 2*1000); //2sec time out for callbacks
+//TestEngine.addTest(true, presenceTest, "[WAC2.0][Orientation] Orientation functions presence test");
+TestEngine.addTest(true, getCurrentOrientationValidParameters, "[WAC2.0][Orientation] Valid parameters");
+//TestEngine.addTest(true, getCurrentOrientationInvalidParamsTest, "[WAC2.0][Orientation] getCurrentOrientation invalid params  test");
+//TestEngine.addTest(true, getCurrentOrientationCheckErrorCallback, "[WAC2.0][Orientation] getCurrentOrientation test");
+//TestEngine.addTest(true, watchOrientationInvalidParamsTest, "[WAC2.0][Orientation] watchOrientation invalid params  test");
+//TestEngine.addTest(true, watchOrientationCheck, "[WAC2.0][Orientation] watchtAcceleration test");
+//TestEngine.addTest(true, clearWatchTest, "[WAC2.0][Orientation] clearWatch test");
+
+
diff --git a/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestTask.js b/tests/smack_security/smackSecurityTest2/js/WAC2.0/TestTask.js
new file mode 100644 (file)
index 0000000..a41cfde
--- /dev/null
@@ -0,0 +1,929 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This file contains the implementation of test task class.
+ *
+ * @author      Shi Hezhang (hezhang.shi@samsung.com)
+ * @author      Pan Rui (r.pan@samsung.com)
+ * @version     0.1
+ */
+
+var TestTask = {
+    TYPE_MISMATCH_ERR: 17,
+    INVALID_VALUES_ERR: 22,
+    task: null,
+    Itask:null,
+    old_task:null,
+    num_tasks:null,
+    found_tasks:null,
+    all_tasks:null,
+    expectedErrorCode: null,
+
+       createTestEvent: function (response)
+    {
+        TestTask.task.createTask({description:'Test Task 1',
+                summary:'Task created to test Itask creation',
+                dueDate: new Date(2009, 3, 30, 10, 0),
+                status:0,
+                priority:0});
+    },
+
+    onSuccessNonExpected: function(response)
+    {
+        TestEngine.test("non expected successCallback invoked", false);
+    },
+
+    onErrorExpected: function(response)
+    {
+        TestEngine.test("expected errorCallback invoked", true);
+        TestEngine.testPresence("error code", response.code);
+        TestEngine.test("Error number, was: " + response.code + ', expected: ' + TestTask.expectedErrorCode, response.code == TestTask.expectedErrorCode);
+    },
+
+    onSuccess: function(response)
+    {
+        TestEngine.test("Callback success", true);
+    },
+
+    onErrorCb: function(response)
+    {
+        TestEngine.logErr("errorCallback invoked [" + response.code + ']');
+    },
+
+    //Cal001
+    test_modulePresence: function()
+    {
+        TestEngine.test("Calendar manager presence", deviceapis.pim.task);
+    },
+
+    //Cal002
+    test_taskProperties: function()
+    {
+        TestEngine.test("test property HIGH_PRIORITY", deviceapis.pim.task.taskproperties.HIGH_PRIORITY === 0);
+        TestEngine.test("test property MEDIUM_PRIORITY", deviceapis.pim.task.taskproperties.MEDIUM_PRIORITY  === 1);
+        TestEngine.test("test property LOW_PRIORITY", deviceapis.pim.task.taskproperties.LOW_PRIORITY === 2);
+        TestEngine.test("test property STATUS_COMPLETED", deviceapis.pim.task.taskproperties.STATUS_COMPLETED === 0);
+        TestEngine.test("test property STATUS_NEEDS_ACTION", deviceapis.pim.task.taskproperties.STATUS_NEEDS_ACTION === 1);
+        TestEngine.test("test property STATUS_IN_PROCESS", deviceapis.pim.task.taskproperties.STATUS_IN_PROCESS === 2);
+        TestEngine.test("test property STATUS_CANCELLED", deviceapis.pim.task.taskproperties.STATUS_CANCELLED === 3);
+    },
+
+    onSuccessGetTask: function (response)
+    {
+        TestEngine.test("Found tasks", response.length > 0);
+        TestTask.task=response[0];
+    },
+
+    acceptError: function()
+    {
+        TestEngine.test("Error as expected", true);
+    },
+
+    rejectSuccess: function()
+    {
+        TestEngine.test("Success - error expected", false);
+    },
+
+    //Cal003
+    test_getTask: function()
+    {
+        var cbObj = TestEngine.registerCallback("getTaskLists",
+            TestTask.rejectSuccess,
+            TestTask.acceptError);
+        deviceapis.pim.task.getTaskLists(cbObj.successCallback, cbObj.errorCallback);
+    },
+
+    //Cal004
+    test_getTaskNoCallbacks: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", "test1");
+    },
+
+    //Cal005
+    test_getTaskInvalidCallbacks: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", 1, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", TestTask.onErrorCb, 2);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", 1, 2);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, deviceapis.pim.task, "getTaskLists", "test1", "test2");
+    },
+
+    //Cal006
+    test_taskMethodsPresence: function()
+    {
+        TestEngine.testPresence("task.createTask presence", TestTask.task.createTask);
+        TestEngine.testPresence("task.addTask presence", TestTask.task.addTask);
+        TestEngine.testPresence("task.updateTask presence", TestTask.task.updateTask);
+        TestEngine.testPresence("task.deleteTask presence", TestTask.task.deleteTask);
+        TestEngine.testPresence("task.findTasks presence", TestTask.task.findTasks);
+    },
+
+    //Cal007
+    test_getTaskName: function()
+    {
+        var cName = TestTask.task.name;
+        TestEngine.test("test getName", isString(cName) && cName.length > 0);
+        TestEngine.log("task name: " + cName);
+    },
+
+    //Cal008
+    test_getTaskType: function ()
+    {
+        var cType = TestTask.task.type;
+        TestEngine.test("test getType", cType === 0 || cType === 1);
+        TestEngine.log("task type: " + cType);
+
+    },
+
+    //Cal009
+    test_taskStaticProperties: function()
+    {
+        TestEngine.test("test property SIM_TASK", TestTask.task.SIM_TASK === 0);
+        TestEngine.test("test property DEVICE_TASK", TestTask.task.DEVICE_TASK === 1);
+    },
+
+    //Cal010
+    test_createEmptyTask: function()
+    {
+        TestTask.Itask = null;
+        TestTask.Itask = TestTask.task.createTask();
+        TestEngine.test("Itask created", TestTask.Itask != null);
+    },
+
+    //Cal011
+    test_taskAttributes: function()
+    {
+        var Itask = TestTask.task.createTask();
+        TestEngine.test("test attribute id - type: " + typeof Itask.id,
+            isString(Itask.id));
+        var oldId = Itask.id;
+        Itask.id = "test" + oldId;
+        TestEngine.test("attribute id is read only", Itask.id === oldId);
+        TestEngine.test("test attribute description - type: " + typeof Itask.description,
+            isString(Itask.description));
+        TestEngine.test("test attribute summary - type: " + typeof Itask.summary,
+            isString(Itask.summary));
+        //TestEngine.test("test attribute categories - type: " + typeof Itask.categories,
+         //   typeof Itask.categories == 'object' && Itask.categories.length == 0);
+        TestEngine.test("test attribute status - type: " + typeof Itask.status + ", value: " + Itask.status,
+            isNumber(Itask.status));
+         TestEngine.test("test attribute priority - type: " + typeof Itask.priority + ", value: " + Itask.priority,
+            isNumber(Itask.priority));
+    },
+
+    //Cal012
+    test_createTask: function()
+    {
+        var date = new Date(2009, 3, 30, 10, 0);
+        var newEvent = TestTask.task.createTask({
+               priority:1,
+               description:'Test Task 1',
+               summary:'Task created to test Itask creation',
+               dueDate: new Date(2009, 3, 30, 10, 0),
+               status:1
+          });
+               TestEngine.test("correct duration", newEvent.priority === 1);
+               TestEngine.test("correct duration", newEvent.status === 1);
+               TestEngine.test("Itask with param created ", newEvent);
+               TestEngine.test("correct description", newEvent.description === 'Test Task 1');
+               TestEngine.test("correct summary", newEvent.summary === 'Task created to test Itask creation');
+               TestEngine.test("correct dueDate", newEvent.dueDate.toString() === date.toString());
+    },
+
+    onSuccessAddTaskCountBefore: function(response)
+    {
+        TestEngine.log("onSuccessAddTaskCountBefore entered");
+        //save current number of tasks
+        TestTask.num_tasks = response.length;
+        //add new Itask
+        var objCb = TestEngine.registerCallback("onSuccessAddTaskCountBefore",
+            TestTask.onSuccessAddTaskAdd,
+            TestTask.onErrorCb);
+        TestTask.task.addTask(objCb.successCallback,
+            objCb.errorCallback,
+            TestTask.Itask);
+    },
+
+    onSuccessAddTaskAdd: function(response)
+    {
+        TestEngine.log("onSuccessAddTaskAdd entered");
+        //count the number of tasks
+        var objCb = TestEngine.registerCallback("onSuccessAddTaskAdd",
+            TestTask.onSuccessAddTaskCountAfter,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    onSuccessAddTaskCountAfter: function(response)
+    {
+        TestEngine.log("onSuccessAddTaskCountAfter entered");
+        TestEngine.test("Number of tasks increased", TestTask.num_tasks+1 == response.length);
+        //validate Itask
+        var eventValidated = false;
+        TestEngine.log("added Itask's id " + TestTask.Itask.id);
+        for (var i in response) {
+            if (TestTask.Itask.id != response[i].id) {
+                continue;
+            }
+            TestEngine.test("description the same", response[i].description === TestTask.Itask.description);
+            TestEngine.test("summary the same", response[i].summary === TestTask.Itask.summary);
+            TestEngine.test("dueDate the same", response[i].dueDate.toString() === TestTask.Itask.dueDate.toString());
+            TestEngine.test("status the same", response[i].status === TestTask.Itask.status);
+            TestEngine.test("priority the same", response[i].priority === TestTask.Itask.priority);
+            eventValidated = true;
+        }
+        TestEngine.test("Task has been validated", eventValidated)
+        TestTask.found_tasks=null;
+        TestTask.num_tasks=null;
+    },
+
+    //Cal013
+    test_addTask1: function()
+    {
+        TestTask.Itask = TestTask.task.createTask({
+                   description:'Task created to test Itask creation',
+                summary:'Test Task 1',
+                dueDate: new Date(2012, 11, 30, 10, 0),
+                status: deviceapis.pim.task.taskproperties.STATUS_COMPLETED,
+                priority: deviceapis.pim.task.taskproperties.HIGH_PRIORITY});
+        //save current number of tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessAddTaskCountBefore,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal014
+    test_addTask2: function()
+    {
+        TestTask.Itask = TestTask.task.createTask({
+                summary:'Test Task 2',
+                description:'Task created to test Itask creation',
+                dueDate: new Date(2012, 11, 30, 10, 0),
+                status: deviceapis.pim.task.taskproperties.STATUS_COMPLETED,
+                priority: deviceapis.pim.task.taskproperties.HIGH_PRIORITY});
+        TestTask.Itask.dueDate = new Date(2012, 10, 30, 10, 0);
+        //save current number of tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessAddTaskCountBefore,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal015
+    test_addTask3: function()
+    {
+        TestTask.Itask = TestTask.task.createTask({
+                summary:'Test Task 3',
+                description:'Task created to test Itask creation',
+                dueDate: new Date(2012, 11, 30, 10, 0),
+                status: 2,
+                priority: 0});
+        //save current number of tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessAddTaskCountBefore,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal016
+    test_addTask4: function()
+    {
+        TestTask.Itask = TestTask.task.createTask({
+                summary:'Test Task 4',
+                description:'Task created to test Itask creation',
+                dueDate: new Date(2012, 11, 30, 10, 0),
+                status: 0,
+                priority: 0});
+
+        //save current number of tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessAddTaskCountBefore,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal017
+    test_addTask5: function()
+    {
+        TestTask.Itask = TestTask.task.createTask({
+                summary:'Test Task 5',
+                description:'Task created to test Itask creation',
+                dueDate: new Date(2012, 11, 30, 10, 0),
+                status: 0,
+                priority: 0});
+        //save current number of tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessAddTaskCountBefore,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback, objCb.errorCallback);
+        //rest of test in callbacks...
+    },
+
+    //Cal018
+    test_addTaskNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask");
+    },
+
+    //Cal019
+    test_addTaskNullCallbacksParams: function()
+    {
+        var Itask = TestTask.createTestEvent();
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", 1, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", "test", TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", "test", TestTask.onErrorCb, Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, "test", Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", 1, 1, Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", "test", "test", Itask);
+    },
+
+    //Cal020
+    test_addTaskWrongEventParam: function()
+    {
+        TestTask.expectedErrorCode = TestTask.INVALID_VALUES_ERR;
+
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, 22);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "addTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, new Date());
+        var objCb1 = TestEngine.registerCallback("Add Itask with null Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.addTask(objCb1.successCallback,
+            objCb1.errorCallback,
+            null);
+
+        var objCb2 = TestEngine.registerCallback("Add Itask with undefined Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.addTask(objCb2.successCallback,
+            objCb2.errorCallback,
+            undefined);
+
+    },
+
+    onSuccessFindAllTasks: function(response)
+    {
+        TestEngine.test("FindAllTasks", response.length > 0);
+        TestTask.all_tasks=response;
+    },
+
+    //Cal021
+    test_findAllTasks: function()
+    {
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessFindAllTasks,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    onSuccessFindTaskWithFilterNoResults: function(response)
+    {
+        TestEngine.test("FindTasks with filter not found results", response.length == 0);
+        TestTask.num_tasks=null;
+    },
+
+    test_FindTasksWithFilterNoResults: function(filter)
+    {
+        if(filter) {
+            for(var i in filter) {
+                TestEngine.log("---Filter---: " + i + " : " + filter[i]);
+            }
+        }
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessFindTaskWithFilterNoResults,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback,
+            filter);
+    },
+
+    onSuccessFindTaskWithFilterSomeResults: function(response)
+    {
+        TestEngine.test("FindTasks with filter found results", response.length > 0);
+        TestTask.num_tasks=null;
+    },
+
+    test_FindTasksWithFilterSomeResults: function(filter)
+    {
+        if(filter) {
+            for(var i in filter) {
+                TestEngine.log("---Filter---: " + i + " : " + filter[i]);
+            }
+        }
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessFindTaskWithFilterSomeResults,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback,
+            filter);
+    },
+
+    //Cal022
+    test_findTasksId: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {id: TestTask.all_tasks[0].id});
+    },
+
+    //Cal023
+    test_findTasksSummary: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {summary:'Test Task 1'});
+    },
+
+    //Cal024
+    test_findTasksDescription: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {description:'Task created to test Itask creation'});
+    },
+
+    //Cal028~~~~~~~~~~~~
+    test_findTasksStatus: function()
+    {
+           var status1 = deviceapis.pim.task.taskproperties.STATUS_COMPLETED;
+           var status2 = deviceapis.pim.task.taskproperties.STATUS_IN_PROCESS;
+           var statusArray =new Array();
+               statusArray.push(status1);
+               statusArray.push(status2);
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {status: statusArray});
+    },
+
+    //Cal028~~~~~~~~~~~~
+    test_findTasksPriority: function()
+    {
+           var priority1 = deviceapis.pim.task.taskproperties.HIGH_PRIORITY;
+           var priority2 = deviceapis.pim.task.taskproperties.MEDIUM_PRIORITY;
+           var priorityArray =new Array();
+               priorityArray.push(priority1);
+               priorityArray.push(priority2);
+        TestEngine.test("Some priority to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {priority: priorityArray});
+    },
+
+
+    //Cal029
+    test_findTasksFullDueDate: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {initialDueDate: new Date(2010, 11, 30, 1, 0),
+             endDueDate: new Date(2012, 11, 30, 23, 0)});
+    },
+
+    //Cal030
+    test_findTasksInitialDueDate: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {initialDueDate: new Date(2010, 11, 30, 1, 0),
+              endDueDate: null});
+    },
+
+    //Cal031
+    test_findTasksEndDueDate: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults(
+            {initialDueDate: null,
+              endDueDate: new Date(2012, 11, 30, 23, 0)});
+    },
+
+    //Cal032
+    test_findTasksEmptyFilter: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterSomeResults({});
+    },
+
+    //Cal033
+    test_findTasksFullDueDateNoResults: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterNoResults(
+            {initialDueDate: new Date(1980, 11, 30, 1, 0),
+             endDueDate: new Date(1980, 11, 30, 23, 0)});
+    },
+
+    //Cal035
+    test_findTasksSummaryNoResults: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterNoResults(
+            {summary:'non existing summary'});
+    },
+
+    //Cal036
+    test_findTasksDescriptionNoResults: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterNoResults(
+            {description:'non existing description'});
+    },
+
+    //Cal037
+    test_findTasksIdNoResults: function()
+    {
+        TestEngine.test("Some tasks to be found", TestTask.all_tasks.length > 0);
+        TestTask.test_FindTasksWithFilterNoResults(
+            {id:"2000000"});
+    },
+
+    //Cal039
+    test_findTasksNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks");
+    },
+
+    //Cal040
+    test_findTasksNullCallbacksParams: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", TestTask.onSuccessNonExpected, 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", TestTask.onSuccessNonExpected, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", 1, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", "test", TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", 1, 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "findTasks", "test", "test");
+    },
+
+    //Cal041
+    test_findTasksWrongFilterParam: function()
+    {
+        TestTask.expectedErrorCode = TestTask.TYPE_MISMATCH_ERR;
+        var objCb1 = TestEngine.registerCallback("Find tasks with null filter param",
+            TestTask.onSuccess,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb1.successCallback,
+            objCb1.errorCallback,
+            null);
+
+        var objCb2 = TestEngine.registerCallback("Find tasks with undefined filter param",
+            TestTask.onSuccess,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb2.successCallback,
+            objCb2.errorCallback,
+            undefined);
+
+        var objCb3 = TestEngine.registerCallback("Find tasks with null filter param",
+            TestTask.onSuccess,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb3.successCallback,
+            objCb3.errorCallback,
+            22);
+
+        var objCb4 = TestEngine.registerCallback("Find tasks with undefined filter param",
+            TestTask.onSuccess,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb4.successCallback,
+            objCb4.errorCallback,
+            "test");
+    },
+
+    //Cal042
+    test_updateTask: function()
+    {
+        if(TestTask.all_tasks.length > 0)
+        {
+            var all=TestTask.all_tasks;
+            TestTask.old_task=all[0];
+
+            //all_tasks.length is added to be sure that it is not
+            //result of previous update
+
+            all[0].description = "Updated"+all.length;
+            all[0].summary = "Updated";
+            TestTask.Itask = all[0];
+
+            var objCb = TestEngine.registerCallback("updateTask",
+                TestTask.onSuccessUpdateTask1,
+                TestTask.onErrorCb);
+            TestTask.task.updateTask(objCb.successCallback,
+                objCb.errorCallback,
+                TestTask.Itask);
+        }
+    },
+
+    onSuccessUpdateTask1: function(response)
+    {
+        TestEngine.log("onSuccessUpdateTask1 entered");
+        //find this Itask
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessUpdateTask2,
+            TestTask.onErrorCb);
+
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback,
+            {description: TestTask.Itask.description,
+                summary: TestTask.Itask.summary});
+    },
+
+    onSuccessUpdateTask2: function(response)
+    {
+        TestEngine.log("onSuccessUpdateTask2 entered");
+        TestTask.found_tasks=response;
+        TestTask.num_tasks = response.length;
+        if(TestTask.found_tasks.length>0)
+        {
+            var f_flag=0;
+            for(var i in TestTask.found_tasks)
+            {
+                if( TestTask.found_tasks[i].description == TestTask.Itask.description &&
+                    TestTask.found_tasks[i].summary == TestTask.Itask.summary)
+                {
+                    TestEngine.test("Update Itask", true);
+                    f_flag=1;
+                }
+            }
+
+            if(f_flag==0)
+            {
+                TestEngine.test("Update Itask", false);
+            }
+        }
+        else
+        {
+            TestEngine.test("Updated tasks found", false);
+        }
+
+        var objCb = TestEngine.registerCallback("updateTask",
+            TestTask.onSuccessUpdateTask3,
+            TestTask.onErrorCb);
+        TestTask.task.updateTask(objCb.successCallback,
+            objCb.errorCallback,
+            TestTask.old_task);
+
+    },
+
+    onSuccessUpdateTask3: function(response)
+    {
+        TestEngine.log("onSuccessUpdateTask3 entered");
+        TestEngine.test("Task restored from update", true);
+    },
+
+    //Cal043
+    test_updateTaskNoParams: function()
+    {
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask");
+    },
+
+    //Cal044
+    test_updateTaskNullCallbacksParams: function()
+    {
+        var Itask = TestTask.createTestEvent();
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", 1, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", "test", TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", "test", TestTask.onErrorCb, Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, "test", Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", 1, 1, Itask);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", "test", "test", Itask);
+    },
+
+    //Cal045
+    test_updateTaskWrongTaskParam: function()
+    {
+        TestTask.expectedErrorCode = TestTask.INVALID_VALUES_ERR;
+
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, 22);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "updateTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, new Date());
+
+        var objCb1 = TestEngine.registerCallback("Update Itask with null Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.updateTask(objCb1.successCallback,
+            objCb1.errorCallback,
+            null);
+
+        var objCb2 = TestEngine.registerCallback("Update Itask with undefined Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.updateTask(objCb2.successCallback,
+            objCb2.errorCallback,
+            undefined);
+    },
+    //Cal046
+    test_deleteTask: function()
+    {
+        //find all tasks
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessDeleteTask1,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    onSuccessDeleteTask1: function(response)
+    {
+        TestEngine.log("onSuccessDeleteTask1 entered");
+        TestEngine.test("FindAllTasks", response.length > 0);
+        TestTask.all_tasks=response;
+
+        if(TestTask.all_tasks.length > 0)
+        {
+            TestTask.old_task=TestTask.all_tasks.length;
+            TestTask.Itask = TestTask.all_tasks[0];
+
+            var objCb = TestEngine.registerCallback("deleteTask",
+                TestTask.onSuccessDeleteTask2,
+                TestTask.onErrorCb);
+            TestTask.task.deleteTask(objCb.successCallback,
+                objCb.errorCallback,
+                TestTask.Itask.id);
+        }
+        else
+        {
+            TestEngine.test("Events for delete found", false);
+        }
+    },
+
+    onSuccessDeleteTask2: function(response)
+    {
+        TestEngine.log("onSuccessDeleteTask2 entered");
+        //check number of tasks now
+        var objCb = TestEngine.registerCallback("findTasks",
+            TestTask.onSuccessDeleteTask3,
+            TestTask.onErrorCb);
+        TestTask.task.findTasks(objCb.successCallback,
+            objCb.errorCallback);
+    },
+
+    onSuccessDeleteTask3: function(response)
+    {
+        TestEngine.log("onSuccessDeleteTask3 entered");
+        TestTask.all_tasks=response;
+        var num_after=response.length;
+        TestEngine.test("deleteTask", num_after + 1 == TestTask.old_task );
+    },
+
+
+    //Cal047
+    test_deleteTaskNoParams: function()
+    {
+        TestEngine.catchErrorType("code", 17, TestTask.task, "deleteTask");
+    },
+
+    //Cal048
+    test_deleteTaskNullCallbacksParams: function()
+    {
+        var Itask = TestTask.createTestEvent();
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", "test", TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", 1, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", "test", TestTask.onErrorCb, 1);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", TestTask.onSuccessNonExpected, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", TestTask.onSuccessNonExpected, "test");
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", TestTask.onSuccessNonExpected, "test", 1);
+    },
+
+    //Cal049
+    test_deleteTaskWrongTaskParam: function()
+    {
+        TestTask.expectedErrorCode = TestTask.INVALID_VALUES_ERR;
+
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb);
+        TestEngine.catchErrorType("code", TestTask.TYPE_MISMATCH_ERR, TestTask.task, "deleteTask", TestTask.onSuccessNonExpected, TestTask.onErrorCb, new Date());
+
+        var objCb1 = TestEngine.registerCallback("Delete Itask with null Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.deleteTask(objCb1.successCallback,
+            objCb1.errorCallback,
+            null);
+
+        var objCb2 = TestEngine.registerCallback("Delete Itask with undefined Itask param",
+            TestTask.onSuccessNonExpected,
+            TestTask.onErrorExpected);
+        TestTask.task.deleteTask(objCb2.successCallback,
+            objCb2.errorCallback,
+            undefined);
+    }
+};
+
+TestEngine.setTestSuiteName("[WAC2.0][Task]");
+
+//Cal001
+//TestEngine.addTest(true,TestTask.test_modulePresence, "[WAC2.0][Task] Test Task");
+//
+////Cal002
+//TestEngine.addTest(true,TestTask.test_taskProperties, "[WAC2.0][Task] Test Itask properties");
+////Cal003
+TestEngine.addTest(true,TestTask.test_getTask, "[WAC2.0][Task] Get task");
+//
+////Cal004
+//TestEngine.addTest(true,TestTask.test_getTaskNoCallbacks, "[WAC2.0][Task] Get task with no callbacks");
+////Cal005
+//TestEngine.addTest(true,TestTask.test_getTaskInvalidCallbacks, "[WAC2.0][Task] Get task with invalid callbacks");
+////Cal006
+//TestEngine.addTest(true,TestTask.test_taskMethodsPresence, "[WAC2.0][Task] Task methods presence");
+////Cal007
+//TestEngine.addTest(true,TestTask.test_getTaskName, "[WAC2.0][Task] Get task name");
+////Cal008
+//TestEngine.addTest(true,TestTask.test_getTaskType, "[WAC2.0][Task] Get task type");
+////Cal009
+//TestEngine.addTest(true,TestTask.test_taskStaticProperties, "[WAC2.0][Task] Task static properties");
+//
+////Cal010
+//TestEngine.addTest(true,TestTask.test_createEmptyTask, "[WAC2.0][Task] Create empty Itask");
+////Cal011
+//TestEngine.addTest(true,TestTask.test_taskAttributes, "[WAC2.0][Task] Itask attributes");
+////Cal012
+//TestEngine.addTest(true,TestTask.test_createTask, "[WAC2.0][Task] Create Itask");
+//
+////Cal013
+//TestEngine.addTest(true,TestTask.test_addTask1, "[WAC2.0][Task] Add event1");
+////Cal014
+//TestEngine.addTest(true,TestTask.test_addTask2, "[WAC2.0][Task] Add event2");
+////Cal015
+//TestEngine.addTest(true,TestTask.test_addTask3, "[WAC2.0][Task] Add event3");
+////Cal016
+//TestEngine.addTest(true,TestTask.test_addTask4, "[WAC2.0][Task] Add event4");
+////Cal017
+//TestEngine.addTest(true,TestTask.test_addTask5, "[WAC2.0][Task] Add event5");
+//
+////Cal018
+//TestEngine.addTest(true,TestTask.test_addTaskNoParams, "[WAC2.0][Task] Add Itask with no params");
+////Cal019
+//TestEngine.addTest(true,TestTask.test_addTaskNullCallbacksParams, "[WAC2.0][Task] Add Itask with wrong callbacks");
+////Cal020
+//TestEngine.addTest(true,TestTask.test_addTaskWrongEventParam, "[WAC2.0][Task] Add Itask with wrong Itask param");
+//
+////Cal021
+//TestEngine.addTest(true,TestTask.test_findAllTasks, "[WAC2.0][Task] Find all tasks");
+////Cal022
+//TestEngine.addTest(true,TestTask.test_findTasksId, "[WAC2.0][Task] Find tasks, filter: id");
+////Cal023
+//TestEngine.addTest(true,TestTask.test_findTasksSummary, "[WAC2.0][Task] Find tasks, filter: summary");
+////Cal024
+//TestEngine.addTest(true,TestTask.test_findTasksDescription, "[WAC2.0][Task] Find tasks, filter: description");
+////Cal025
+//TestEngine.addTest(true,TestTask.test_findTasksStatus, "[WAC2.0][Task] Find tasks, filter: status");
+//
+//TestEngine.addTest(true,TestTask.test_findTasksPriority, "[WAC2.0][Task] Find tasks, filter: priority");
+////Cal030
+//TestEngine.addTest(true,TestTask.test_findTasksInitialDueDate, "[WAC2.0][Task] Find tasks, filter: initialDueDate");
+////Cal031
+//TestEngine.addTest(true,TestTask.test_findTasksEndDueDate, "[WAC2.0][Task] Find tasks, filter: endDueDate");
+////Cal032
+//TestEngine.addTest(true,TestTask.test_findTasksEmptyFilter, "[WAC2.0][Task] Find tasks, filter: empty filter");
+//
+////Cal035
+//TestEngine.addTest(true,TestTask.test_findTasksSummaryNoResults, "[WAC2.0][Task] Find tasks, no results, filter: summary");
+////Cal036
+//TestEngine.addTest(true,TestTask.test_findTasksDescriptionNoResults, "[WAC2.0][Task] Find tasks, no results, filter: description");
+////Cal039
+//TestEngine.addTest(true,TestTask.test_findTasksNoParams, "[WAC2.0][Task] Find tasks with no params");
+////Cal040
+//TestEngine.addTest(true,TestTask.test_findTasksNullCallbacksParams, "[WAC2.0][Task] Find tasks with wrong callbacks");
+////Cal041
+//TestEngine.addTest(true,TestTask.test_findTasksWrongFilterParam, "[WAC2.0][Task] Find tasks with wrong filter param");
+//
+//TestEngine.addTest(true,TestTask.test_updateTask, "[WAC2.0][Task] Update Itask");
+////Cal043
+//TestEngine.addTest(true,TestTask.test_updateTaskNoParams, "[WAC2.0][Task] Update Itask with no params");
+////Cal044
+//TestEngine.addTest(true,TestTask.test_updateTaskNullCallbacksParams, "[WAC2.0][Task] Update Itask with wrong callbacks");
+////Cal045
+//TestEngine.addTest(true,TestTask.test_updateTaskWrongTaskParam, "[WAC2.0][Task] Update Itask with wrong Itask param");
+//
+////Cal046
+//TestEngine.addTest(true,TestTask.test_deleteTask, "[WAC2.0][Task] Delete Itask");
+////Cal047
+//TestEngine.addTest(true,TestTask.test_deleteTaskNoParams, "[WAC2.0][Task] Delete Itask with no params");
+////Cal048
+//TestEngine.addTest(true,TestTask.test_deleteTaskNullCallbacksParams, "[WAC2.0][Task] Delete Itask with wrong callbacks");
+////Cal049
+//TestEngine.addTest(true,TestTask.test_deleteTaskWrongTaskParam, "[WAC2.0][Task] Delete Itask with wrong Itask param");
diff --git a/tests/smack_security/smackSecurityTest2/js/include1.js b/tests/smack_security/smackSecurityTest2/js/include1.js
new file mode 100644 (file)
index 0000000..45ac87e
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestFilesystem.js")
+
+IncludeJavaScript("js/WAC2.0/CloseCallback.js")
diff --git a/tests/smack_security/smackSecurityTest2/js/include10.js b/tests/smack_security/smackSecurityTest2/js/include10.js
new file mode 100644 (file)
index 0000000..b74692e
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestMessaging.js")
+
+IncludeJavaScript("js/WAC2.0/CloseCallback.js")
diff --git a/tests/smack_security/smackSecurityTest2/js/include2.js b/tests/smack_security/smackSecurityTest2/js/include2.js
new file mode 100644 (file)
index 0000000..c3fe9e6
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestCalendar.js")
+
+IncludeJavaScript("js/WAC2.0/CloseCallback.js")
diff --git a/tests/smack_security/smackSecurityTest2/js/include3.js b/tests/smack_security/smackSecurityTest2/js/include3.js
new file mode 100644 (file)
index 0000000..752d596
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestContact.js")
+
+IncludeJavaScript("js/WAC2.0/CloseCallback.js")
diff --git a/tests/smack_security/smackSecurityTest2/js/include4.js b/tests/smack_security/smackSecurityTest2/js/include4.js
new file mode 100644 (file)
index 0000000..e30035d
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestAccelerometer.js")
+
+IncludeJavaScript("js/WAC2.0/CloseCallback.js")
diff --git a/tests/smack_security/smackSecurityTest2/js/include5.js b/tests/smack_security/smackSecurityTest2/js/include5.js
new file mode 100644 (file)
index 0000000..8ffb15a
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestOrientation.js")
+
+IncludeJavaScript("js/WAC2.0/CloseCallback.js")
diff --git a/tests/smack_security/smackSecurityTest2/js/include6.js b/tests/smack_security/smackSecurityTest2/js/include6.js
new file mode 100644 (file)
index 0000000..817cd37
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestTask.js")
+
+IncludeJavaScript("js/WAC2.0/CloseCallback.js")
diff --git a/tests/smack_security/smackSecurityTest2/js/include7.js b/tests/smack_security/smackSecurityTest2/js/include7.js
new file mode 100644 (file)
index 0000000..e264754
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestCamera.js")
+
+IncludeJavaScript("js/WAC2.0/CloseCallback.js")
diff --git a/tests/smack_security/smackSecurityTest2/js/include8.js b/tests/smack_security/smackSecurityTest2/js/include8.js
new file mode 100644 (file)
index 0000000..e2eaaf6
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestDeviceInteraction.js")
+
+IncludeJavaScript("js/WAC2.0/CloseCallback.js")
diff --git a/tests/smack_security/smackSecurityTest2/js/include9.js b/tests/smack_security/smackSecurityTest2/js/include9.js
new file mode 100644 (file)
index 0000000..30e639c
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+function IncludeJavaScript(jsFile)
+{
+    document.write('<script type="text/javascript" src="' + jsFile + '"></script>');
+}
+
+var VERBOSE = 1;
+
+IncludeJavaScript("js/TestEngine.js")
+IncludeJavaScript("js/WAC2.0/TestDevicestatus.js")
+
+IncludeJavaScript("js/WAC2.0/CloseCallback.js")
diff --git a/tests/smack_security/smackSecurityTest2/js/jquery.js b/tests/smack_security/smackSecurityTest2/js/jquery.js
new file mode 100644 (file)
index 0000000..381ebfe
--- /dev/null
@@ -0,0 +1,40 @@
+/*!
+ * Copyright (C) 2011, John Resig
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
+ * this software and associated documentation files (the "Software"), to deal in
+ * the Software without restriction, including without limitation the rights to
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+ * of the Software, and to permit persons to whom the Software is furnished to do
+ * so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+/*!
+ * jQuery JavaScript Library v1.7
+ * http://jquery.com/
+ *
+ * Copyright 2011, John Resig
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ * Copyright 2011, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ *
+ * Date: Thu Nov 3 16:18:21 2011 -0400
+ */
+
+(function(a,b){function cA(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cx(a){if(!cm[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cn||(cn=c.createElement("iframe"),cn.frameBorder=cn.width=cn.height=0),b.appendChild(cn);if(!co||!cn.createElement)co=(cn.contentWindow||cn.contentDocument).document,co.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),co.close();d=co.createElement(a),co.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cn)}cm[a]=e}return cm[a]}function cw(a,b){var c={};f.each(cs.concat.apply([],cs.slice(0,b)),function(){c[this]=a});return c}function cv(){ct=b}function cu(){setTimeout(cv,0);return ct=f.now()}function cl(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ck(){try{return new a.XMLHttpRequest}catch(b){}}function ce(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cd(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function cc(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bG.test(a)?d(a,e):cc(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)cc(a+"["+e+"]",b[e],c,d);else d(a,b)}function cb(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function ca(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bV,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=ca(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=ca(a,c,d,e,"*",g));return l}function b_(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bR),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bE(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bz:bA;if(d>0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bB(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function br(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bi,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bq(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bp(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bp)}function bp(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bo(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bn(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bm(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bl(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function X(a){var b=Y.split(" "),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function W(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(R.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(){return!0}function M(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function K(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(K,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z]|[0-9])/ig,x=/^-ms-/,y=function(a,b){return(b+"").toUpperCase()},z=d.userAgent,A,B,C,D=Object.prototype.toString,E=Object.prototype.hasOwnProperty,F=Array.prototype.push,G=Array.prototype.slice,H=String.prototype.trim,I=Array.prototype.indexOf,J={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=n.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7",length:0,size:function(){return this.length},toArray:function(){return G.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?F.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),B.add(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(G.apply(this,arguments),"slice",G.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:F,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;B.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!B){B=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",C,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",C),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&K()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return a!=null&&m.test(a)&&!isNaN(a)},type:function(a){return a==null?String(a):J[D.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!E.call(a,"constructor")&&!E.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||E.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(x,"ms-").replace(w,y)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:H?function(a){return a==null?"":H.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?F.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(I)return I.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=G.call(arguments,2),g=function(){return a.apply(c,f.concat(G.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=s.exec(a)||t.exec(a)||u.exec(a)||a.indexOf("compatible")<0&&v.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){J["[object "+b+"]"]=b.toLowerCase()}),A=e.uaMatch(z),A.browser&&(e.browser[A.browser]=!0,e.browser.version=A.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?C=function(){c.removeEventListener("DOMContentLoaded",C,!1),e.ready()}:c.attachEvent&&(C=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",C),e.ready())}),typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return e});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){return i.done.apply(i,arguments).fail.apply(i,arguments)},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var a=c.createElement("div"),b=c.documentElement,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;a.setAttribute("className","t"),a.innerHTML="   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/><nav></nav>",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,unknownElems:!!a.getElementsByTagName("nav").length,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",enctype:!!c.createElement("form").enctype,submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.lastChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},m&&f.extend(p,{position:"absolute",left:"-999px",top:"-999px"});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;f(function(){var a,b,d,e,g,h,i=1,j="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",l="visibility:hidden;border:0;",n="style='"+j+"border:5px solid #000;padding:0;'",p="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>";m=c.getElementsByTagName("body")[0];!m||(a=c.createElement("div"),a.style.cssText=l+"width:0;height:0;position:static;top:0;margin-top:"+i+"px",m.insertBefore(a,m.firstChild),o=c.createElement("div"),o.style.cssText=j+l,o.innerHTML=p,a.appendChild(o),b=o.firstChild,d=b.firstChild,g=b.nextSibling.firstChild.firstChild,h={doesNotAddBorder:d.offsetTop!==5,doesAddBorderForTableAndCells:g.offsetTop===5},d.style.position="fixed",d.style.top="20px",h.fixedPosition=d.offsetTop===20||d.offsetTop===15,d.style.position=d.style.top="",b.style.overflow="hidden",b.style.position="relative",h.subtractsBorderForOverflowNotVisible=d.offsetTop===-5,h.doesNotIncludeMarginInBodyOffset=m.offsetTop!==i,m.removeChild(a),o=a=null,f.extend(k,h))}),o.innerHTML="",n.removeChild(o),o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[f.expando]:a[f.expando]&&f.expando,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[f.expando]=n=++f.uuid:n=f.expando),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[f.expando]:f.expando;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)?b=b:b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" "));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[f.expando]:a.removeAttribute?a.removeAttribute(f.expando):a[f.expando]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];if(!arguments.length){if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}return b}e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!a||j===3||j===8||j===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g},removeAttr:function(a,b){var c,d,e,g,h=0;if(a.nodeType===1){d=(b||"").split(p),g=d.length;for(;h<g;h++)e=d[h].toLowerCase(),c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1)}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return b;h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/\.(.*)$/,A=/^(?:textarea|input|select)$/i,B=/\./g,C=/ /g,D=/[^\w\s.|`]/g,E=/^([^\.]*)?(?:\.(.+))?$/,F=/\bhover(\.\S+)?/,G=/^key/,H=/^(?:mouse|contextmenu)|click/,I=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,J=function(a){var b=I.exec(a);b&&
+(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},K=function(a,b){return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||a.id===b[2])&&(!b[3]||b[3].test(a.className))},L=function(a){return f.event.special.hover?a:a.replace(F,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=L(c).split(" ");for(k=0;k<c.length;k++){l=E.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,namespace:n.join(".")},p),g&&(o.quick=J(g),!o.quick&&f.expr.match.POS.test(g)&&(o.isPositional=!0)),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d){var e=f.hasData(a)&&f._data(a),g,h,i,j,k,l,m,n,o,p,q;if(!!e&&!!(m=e.events)){b=L(b||"").split(" ");for(g=0;g<b.length;g++){h=E.exec(b[g])||[],i=h[1],j=h[2];if(!i){j=j?"."+j:"";for(l in m)f.event.remove(a,l+j,c,d);return}n=f.event.special[i]||{},i=(d?n.delegateType:n.bindType)||i,p=m[i]||[],k=p.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;if(c||j||d||n.remove)for(l=0;l<p.length;l++){q=p[l];if(!c||c.guid===q.guid)if(!j||j.test(q.namespace))if(!d||d===q.selector||d==="**"&&q.selector)p.splice(l--,1),q.selector&&p.delegateCount--,n.remove&&n.remove.call(a,q)}else p.length=0;p.length===0&&k!==p.length&&((!n.teardown||n.teardown.call(a,j)===!1)&&f.removeEvent(a,i,e.handle),delete m[i])}f.isEmptyObject(m)&&(o=e.handle,o&&(o.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"",(g||!e)&&c.preventDefault();if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,n=null;for(m=e.parentNode;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length;l++){m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d);if(c.isPropagationStopped())break}c.type=h,c.isDefaultPrevented()||(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=(f.event.special[c.type]||{}).handle,j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click"))for(m=c.target;m!=this;m=m.parentNode||this){o={},q=[];for(k=0;k<e;k++)r=d[k],s=r.selector,t=o[s],r.isPositional?t=(t||(o[s]=f(s))).index(m)>=0:t===b&&(t=o[s]=r.quick?K(m,r.quick):f(m).is(s)),t&&q.push(r);q.length&&j.push({elem:m,matches:q})}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){p=j[k],c.currentTarget=p.elem;for(l=0;l<p.matches.length&&!c.isImmediatePropagationStopped();l++){r=p.matches[l];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=(i||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement wheelDelta".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},focus:{delegateType:"focusin",noBubble:!0},blur:{delegateType:"focusout",noBubble:!0},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?N:M):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=N;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=N;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=N,this.stopPropagation()},isDefaultPrevented:M,isPropagationStopped:M,isImmediatePropagationStopped:M},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]=f.event.special[b]={delegateType:b,bindType:b,handle:function(a){var b=this,c=a.relatedTarget,d=a.handleObj,e=d.selector,g,h;if(!c||d.origType===a.type||c!==b&&!f.contains(b,c))g=a.type,a.type=d.origType,h=d.handler.apply(this,arguments),a.type=g;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(A.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;A.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return A.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=M;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=M);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),G.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),H.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw"Syntax error, unrecognized expression: "+a};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var O=/Until$/,P=/^(?:parents|prevUntil|prevAll)/,Q=/,/,R=/^.[^:#\[\.,]*$/,S=Array.prototype.slice,T=f.expr.match.POS,U={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(W(this,a,!1),"not",a)},filter:function(a){return this.pushStack(W(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?T.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=T.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(V(c[0])||V(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var Y="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",Z=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,_=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,ba=/<([\w:]+)/,bb=/<tbody/i,bc=/<|&#?\w+;/,bd=/<(?:script|style)/i,be=/<(?:script|object|embed|option|style)/i,bf=new RegExp("<(?:"+Y.replace(" ","|")+")","i"),bg=/checked\s*(?:[^=]|=\s*.checked.)/i,bh=/\/(java|ecma)script/i,bi=/^\s*<!(?:\[CDATA\[|\-\-)/,bj={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bk=X(c);bj.optgroup=bj.option,bj.tbody=bj.tfoot=bj.colgroup=bj.caption=bj.thead,bj.th=bj.td,f.support.htmlSerialize||(bj._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){f(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after"
+,arguments);a.push.apply(a,f(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Z,""):null;if(typeof a=="string"&&!bd.test(a)&&(f.support.leadingWhitespace||!$.test(a))&&!bj[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(_,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bg.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bl(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,br)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!be.test(j)&&(f.support.checkClone||!bg.test(j))&&!f.support.unknownElems&&bf.test(j)&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bn(a,d),e=bo(a),g=bo(d);for(h=0;e[h];++h)g[h]&&bn(e[h],g[h])}if(b){bm(a,d);if(c){e=bo(a),g=bo(d);for(h=0;e[h];++h)bm(e[h],g[h])}}e=g=null;return d},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!bc.test(k))k=b.createTextNode(k);else{k=k.replace(_,"<$1></$2>");var l=(ba.exec(k)||["",""])[1].toLowerCase(),m=bj[l]||bj._default,n=m[0],o=b.createElement("div");b===c?bk.appendChild(o):X(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=bb.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&$.test(k)&&o.insertBefore(b.createTextNode($.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bq(k[i]);else bq(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bh.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bs=/alpha\([^)]*\)/i,bt=/opacity=([^)]*)/,bu=/([A-Z]|^ms)/g,bv=/^-?\d+(?:px)?$/i,bw=/^-?\d/,bx=/^([\-+])=([\-+.\de]+)/,by={position:"absolute",visibility:"hidden",display:"block"},bz=["Left","Right"],bA=["Top","Bottom"],bB,bC,bD;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bB(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bx.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bB)return bB(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bE(a,b,d);f.swap(a,by,function(){e=bE(a,b,d)});return e}},set:function(a,b){if(!bv.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bt.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bs,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bs.test(g)?g.replace(bs,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bB(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bC=function(a,c){var d,e,g;c=c.replace(bu,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bD=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bv.test(f)&&bw.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bB=bC||bD,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bF=/%20/g,bG=/\[\]$/,bH=/\r?\n/g,bI=/#.*$/,bJ=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bK=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bL=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bM=/^(?:GET|HEAD)$/,bN=/^\/\//,bO=/\?/,bP=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bQ=/^(?:select|textarea)/i,bR=/\s+/,bS=/([?&])_=[^&]*/,bT=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bU=f.fn.load,bV={},bW={},bX,bY,bZ=["*/"]+["*"];try{bX=e.href}catch(b$){bX=c.createElement("a"),bX.href="",bX=bX.href}bY=bT.exec(bX.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bU)return bU.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bP,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bQ.test(this.nodeName)||bK.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bH,"\r\n")}}):{name:b.name,value:c.replace(bH,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?cb(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),cb(a,b);return a},ajaxSettings:{url:bX,isLocal:bL.test(bY[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bZ},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:b_(bV),ajaxTransport:b_(bW),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cd(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=ce(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bJ.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bI,"").replace(bN,bY[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bR),d.crossDomain==null&&(r=bT.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bY[1]&&r[2]==bY[2]&&(r[3]||(r[1]==="http:"?80:443))==(bY[3]||(bY[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),ca(bV,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bM.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bO.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bS,"$1_="+x);d.url=y+(y===d.url?(bO.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bZ+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=ca(bW,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){s<2?w(-1,z):f.error(z)}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)cc(g,a[g],c,e);return d.join("&").replace(bF,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cf=f.now(),cg=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cf++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cg.test(b.url)||e&&cg.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cg,l),b.url===j&&(e&&(k=k.replace(cg,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ch=a.ActiveXObject?function(){for(var a in cj)cj[a](0,1)}:!1,ci=0,cj;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ck()||cl()}:ck,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ch&&delete cj[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++ci,ch&&(cj||(cj={},f(a).unload(ch)),cj[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cm={},cn,co,cp=/^(?:toggle|show|hide)$/,cq=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cr,cs=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],ct;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cw("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cx(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cw("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cw("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cx(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cp.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=cq.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cw("show",1),slideUp:cw("hide",1),slideToggle:cw("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=ct||cu(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cr&&(cr=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=ct||cu(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cr),cr=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now))}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cy=/^t(?:able|d|h)$/i,cz=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cA(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cy.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cz.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cz.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cA(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cA(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window);
diff --git a/tests/smack_security/wrt-tests-security-smack.sh b/tests/smack_security/wrt-tests-security-smack.sh
new file mode 100755 (executable)
index 0000000..990d71e
--- /dev/null
@@ -0,0 +1,183 @@
+#/bin/sh
+
+TEST_RESULT_DIR=
+TEST_TYPE="text"
+
+while getopts "o:d:" opts
+do
+    case "$opts" in
+        d)  echo "Output directory: $OPTARG"
+            TEST_RESULT_DIR="$OPTARG" ;;
+        o)  echo "Output type: $OPTARG"
+            TEST_TYPE="$OPTARG" ;;
+        [?])echo "Usage $0 [-o output_type] [-d output_directory]"
+            exit 1;;
+    esac
+done
+
+result=`rpm -qa | grep wrt-extra`
+if [ -z "$result" ]; then
+    echo "You must install wrt-extra before run this script";
+    exit;
+fi
+
+export DPL_USE_OLD_STYLE_LOGS=0
+export DPL_TEST_OUTPUT="$TEST_TYPE"
+
+function task_info(){
+    text="$1"
+    status="$2"
+    if [ $status -eq 0 ]; then
+        echo -e "\033[32m$text    \033[0m [ \033[32mDONE\033[0m ] ";
+    else
+        echo -e "\033[32m$text    \033[0m [ \033[31mFAIL\033[0m ] ";
+    fi
+}
+
+function error_msg(){
+    text="$1"
+    echo -e "\031[32m$text\033[0m] ";
+}
+
+function set_up_env(){
+    wrt_reset_all.sh
+    if [ -e /usr/etc/ace/WAC2.0Policy.back ]; then
+        error_msg "Policy backup already exists";
+    else
+        mv /usr/etc/ace/WAC2.0Policy.xml /usr/etc/ace/WAC2.0Policy.back
+        task_info "Create policy backup" $?
+    fi
+
+    cp /usr/etc/ace/PermitAllPolicy.xml /usr/etc/ace/WAC2.0Policy.xml
+    task_info "Set up test policy file" $?
+
+    wrt_security_change_policy.sh
+    task_info "Reset policy settings in daemon" $?
+}
+
+function set_up_nodevcap_env(){
+    if [ -d /tmp/smack.back ]; then
+        error_msg "Backup directory with smack files already exists.";
+    else
+        mkdir -p /tmp/smack.back
+        cp /usr/share/privilege-control/*.smack /tmp/smack.back/
+        task_info "Create smack files backup" $?
+        echo -n > /usr/share/privilege-control/accelerometer.smack
+        echo -n > /usr/share/privilege-control/filesystem.read.smack
+        echo -n > /usr/share/privilege-control/filesystem.write.smack
+        echo -n > /usr/share/privilege-control/orientation.smack
+        echo -n > /usr/share/privilege-control/pim.calendar.read.smack
+        echo -n > /usr/share/privilege-control/pim.calendar.write.smack
+        echo -n > /usr/share/privilege-control/pim.contact.read.smack
+        echo -n > /usr/share/privilege-control/pim.contact.write.smack
+        echo -n > /usr/share/privilege-control/pim.task.read.smack
+        echo -n > /usr/share/privilege-control/pim.task.write.smack
+        task_info "Replace smack files with empty one..." $?
+    fi
+}
+
+function move_result(){
+    source=`pwd`
+    echo "Function move_resutl. Source: $source"
+    if [ "x$TEST_RESULT_DIR" = "x" ]; then
+        return
+    fi
+
+    if [ "x$TEST_TYPE" != "x" ]; then
+        echo "Move: mv results.xml $TEST_RESULT_DIR/$1.$TEST_TYPE"
+        mv results.xml "$TEST_RESULT_DIR/$1.$TEST_TYPE"
+    fi
+}
+
+function run_widget(){
+    #cut -d: -f2
+    uid=`echo $1 | awk -F ": " '{print $2}'`
+    if echo $uid | egrep -q '^[0-9]+$'; then
+        echo "First widget id: $uid"
+        wrt-client -l $uid
+        result_code=$?
+        echo "wrt-client exit with code $result_code";
+    else
+        echo "Result $1"
+    fi
+    move_result "smack_$uid"
+}
+
+function run_widget_nosmack(){
+    #cut -d: -f2
+    uid=`echo $1 | awk -F ": " '{print $2}'`
+    if echo $uid | egrep -q '^[0-9]+$'; then
+        echo "First widget id: $uid"
+        wrt-client -l $uid
+        result_code=$?
+        echo "wrt-client exit with code $result_code";
+        if [ $result_code -eq 139 ]; then
+            echo "Widget ended with crash (as expected)             [  OK  ]";
+        fi
+    else
+        echo "Result $1"
+    fi
+    move_result "nosmack_$uid"
+}
+
+function restore_env(){
+    cp /usr/etc/ace/WAC2.0Policy.back /usr/etc/ace/WAC2.0Policy.xml && rm /usr/etc/ace/WAC2.0Policy.back
+    task_info "Restore policy file and remove backup copy" $?
+    cp /tmp/smack.back/* /usr/share/privilege-control/ && rm /tmp/smack.back -rf
+    task_info "Restore smack file and remove backup copy" $?
+    wrt_security_change_policy.sh
+    task_info "Reset policy settings in daemon" $?
+}
+
+if [ "x$1" = "xfix" ]; then
+    echo "I will try to restore evironment";
+    restore_env
+    exit 0;
+fi
+
+set_up_env
+
+echo "Widget installation"
+result0=`wrt-installer -if /opt/apps/widget/tests/smack/smacksecurity0.wgt`
+task_info "Widget smacksecurity0.wgt installed" $?
+result1=`wrt-installer -if /opt/apps/widget/tests/smack/smacksecurity1.wgt`
+task_info "Widget smacksecurity1.wgt installed" $?
+result2=`wrt-installer -if /opt/apps/widget/tests/smack/smacksecurity2.wgt`
+task_info "Widget smacksecurity2.wgt installed" $?
+result3=`wrt-installer -if /opt/apps/widget/tests/smack/smacksecurity3.wgt`
+task_info "Widget smacksecurity3.wgt installed" $?
+result4=`wrt-installer -if /opt/apps/widget/tests/smack/smacksecurity4.wgt`
+task_info "Widget smacksecurity4.wgt installed" $?
+result5=`wrt-installer -if /opt/apps/widget/tests/smack/smacksecurity5.wgt`
+task_info "Widget smacksecurity5.wgt installed" $?
+result6=`wrt-installer -if /opt/apps/widget/tests/smack/smacksecurity6.wgt`
+task_info "Widget smacksecurity6.wgt installed" $?
+result7=`wrt-installer -if /opt/apps/widget/tests/smack/smacksecurity7.wgt`
+task_info "Widget smacksecurity7.wgt installed" $?
+result8=`wrt-installer -if /opt/apps/widget/tests/smack/smacksecurity8.wgt`
+task_info "Widget smacksecurity8.wgt installed" $?
+result9=`wrt-installer -if /opt/apps/widget/tests/smack/smacksecurity9.wgt`
+task_info "Widget smacksecurity9.wgt installed" $?
+result10=`wrt-installer -if /opt/apps/widget/tests/smack/smacksecurity10.wgt`
+task_info "Widget smacksecurity10.wgt installed" $?
+
+echo "**************************************************"
+echo "**************** Start tests *********************"
+echo "**************************************************"
+
+run_widget "$result0"
+
+set_up_nodevcap_env
+
+run_widget_nosmack "$result1"
+run_widget_nosmack "$result2"
+run_widget_nosmack "$result3"
+run_widget_nosmack "$result4"
+run_widget_nosmack "$result5"
+run_widget_nosmack "$result6"
+run_widget_nosmack "$result7"
+run_widget_nosmack "$result8"
+run_widget_nosmack "$result9"
+run_widget_nosmack "$result10"
+
+restore_env
diff --git a/tests/wrt-tests-security-all.sh b/tests/wrt-tests-security-all.sh
new file mode 100755 (executable)
index 0000000..a21e907
--- /dev/null
@@ -0,0 +1,37 @@
+#!/bin/sh
+
+#####################################################################
+# Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#####################################################################
+
+
+#####################################################################
+#   author: pawel.polawski@partner.samsung.com
+#####################################################################
+
+security-tests.sh ace --output=text
+sleep 1
+
+security-tests.sh ace-client --output=text
+sleep 1
+
+security-tests.sh ace-settings --output=text
+sleep 1
+
+security-tests.sh ace-install --output=text
+sleep 1
+
+security-tests.sh security-daemon --output=text
+sleep 1
diff --git a/wrt_ocsp/CMakeLists.txt b/wrt_ocsp/CMakeLists.txt
new file mode 100644 (file)
index 0000000..e03d379
--- /dev/null
@@ -0,0 +1 @@
+ADD_SUBDIRECTORY(src)
\ No newline at end of file
diff --git a/wrt_ocsp/include/wrt_ocsp_api.h b/wrt_ocsp/include/wrt_ocsp_api.h
new file mode 100644 (file)
index 0000000..856d97b
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ *    Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        wrt_oscp_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This is C api for WRT OCSP
+ */
+#ifndef WRT_OCSP_API_H
+#define WRT_OCSP_API_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum{
+  WRT_OCSP_OK,
+  WRT_OCSP_INVALID_ARGUMENTS,
+  WRT_OCSP_INTERNAL_ERROR
+}wrt_ocsp_return_t;
+
+typedef int wrt_ocsp_widget_handle_t;
+typedef enum {
+  //The certificate has not been revoked.
+  WRT_OCSP_WIDGET_VERIFICATION_STATUS_GOOD,
+
+  //The certificate has been revoked.
+  WRT_OCSP_WIDGET_VERIFICATION_STATUS_REVOKED
+
+
+}wrt_ocsp_widget_verification_status_t;
+
+//-------------Initialization and shutdown-------------------
+/*
+ * Establishes connection to security server. Must be called only once.
+ * Returns WRT_OCSP_OK or error
+ */
+wrt_ocsp_return_t wrt_ocsp_initialize(void);
+
+/*
+ * Deinitializes internal structures. Must be called only once.
+ * Returns WRT_OCSP_OK or error
+ */
+
+wrt_ocsp_return_t wrt_ocsp_shutdown(void);
+
+//-------------Widget verification------------------------------
+/*
+ * Requests verification for widget identified with 'handle'.
+ * 'status holds server response.
+ * Returns WRT_OCSP_OK or error
+ */
+
+wrt_ocsp_return_t wrt_ocsp_verify_widget(wrt_ocsp_widget_handle_t handle,
+                                         wrt_ocsp_widget_verification_status_t* status);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif //WRT_OCSP_API_H
diff --git a/wrt_ocsp/src/CMakeLists.txt b/wrt_ocsp/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..35bc91b
--- /dev/null
@@ -0,0 +1,60 @@
+include(FindPkgConfig)
+
+PKG_CHECK_MODULES(WRT_OCSP_DEPS
+    dpl-efl
+    dpl-dbus-efl
+    REQUIRED
+    )
+
+SET(WRT_OCSP_DIR
+    ${PROJECT_SOURCE_DIR}/wrt_ocsp
+    )
+
+SET(WRT_OCSP_SRC_DIR
+    ${WRT_OCSP_DIR}/src
+    )
+
+SET(WRT_OCSP_INCLUDE_DIR
+    ${WRT_OCSP_DIR}/include
+    )
+
+SET(WRT_OCSP_SOURCES
+    ${COMMUNICATION_CLIENT_SOURCES}
+    ${WRT_OCSP_SRC_DIR}/wrt_ocsp_api.cpp
+    )
+
+SET(WRT_OCSP_INCLUDES
+    ${WRT_OCSP_DEPS_INCLUDE_DIRS}
+    ${WRT_OCSP_INCLUDE_DIR}
+    ${COMMUNICATION_CLIENT_INCLUDES}
+    ${PROJECT_SOURCE_DIR}/src/services/ocsp
+    ${PROJECT_SOURCE_DIR}/src/services/ocsp/dbus/api
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus
+    )
+
+ADD_DEFINITIONS(${WRT_OCSP_DEPS_CFLAGS})
+ADD_DEFINITIONS(${WRT__CFLAGS_OTHER})
+
+INCLUDE_DIRECTORIES(${WRT_OCSP_INCLUDES})
+
+ADD_LIBRARY(${TARGET_WRT_OCSP_LIB} SHARED ${WRT_OCSP_SOURCES})
+
+SET_TARGET_PROPERTIES(${TARGET_WRT_OCSP_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_WRT_OCSP_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+TARGET_LINK_LIBRARIES(${TARGET_WRT_OCSP_LIB}
+    ${WRT_OCSP_DEPS_LIBRARIES}
+    ${WRT_OCSP_DEPS_LDFLAGS}
+    )
+
+INSTALL(TARGETS ${TARGET_WRT_OCSP_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+    ${WRT_OCSP_INCLUDE_DIR}/wrt_ocsp_api.h
+    DESTINATION include/wrt-ocsp
+    )
diff --git a/wrt_ocsp/src/wrt_ocsp_api.cpp b/wrt_ocsp/src/wrt_ocsp_api.cpp
new file mode 100644 (file)
index 0000000..8c1dd1a
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        wrt_ocsp_api.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of WRT OCSP api
+ */
+
+#include <dpl/log/log.h>
+#include <dpl/dbus/dbus_client.h>
+#include "ocsp_server_api.h"
+#include "SecurityCommunicationClient.h"
+
+#include "wrt_ocsp_api.h"
+
+static WrtSecurity::Communication::Client *communicationClient = NULL;
+
+wrt_ocsp_return_t wrt_ocsp_initialize(void){
+#ifdef __SUPPORT_OCSP__
+    if (NULL != communicationClient) {
+        LogError("wrt_ocsp_api already initialized");
+        return WRT_OCSP_INTERNAL_ERROR;
+    }
+
+    Try {
+        communicationClient = new WrtSecurity::Communication::Client(WrtSecurity::OcspServerApi::INTERFACE_NAME());
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Can't connect to daemon");
+        return WRT_OCSP_INTERNAL_ERROR;
+    }
+#endif
+    LogInfo("Initialized");
+    return WRT_OCSP_OK;
+}
+
+wrt_ocsp_return_t wrt_ocsp_shutdown(void){
+#ifdef __SUPPORT_OCSP__    
+    if (NULL == communicationClient) {
+        LogError("wrt_ocsp_api not initialized");
+        return WRT_OCSP_INTERNAL_ERROR;
+    }
+    delete communicationClient;
+    communicationClient = NULL;
+#endif
+    LogInfo("Shutdown");
+    return WRT_OCSP_OK;
+}
+
+wrt_ocsp_return_t wrt_ocsp_verify_widget(wrt_ocsp_widget_handle_t handle,
+                                         wrt_ocsp_widget_verification_status_t* status){
+
+    LogInfo("Verifying");
+    if (NULL == status) {
+        LogError("Invalid arguments");
+        return WRT_OCSP_INVALID_ARGUMENTS;
+    }
+    int intResponse;
+
+#ifdef __SUPPORT_OCSP__ 
+    Try {
+        communicationClient->call(WrtSecurity::OcspServerApi::CHECK_ACCESS_METHOD(),
+                                  handle,
+                                  &intResponse);
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Problem with connection to daemon");
+        return WRT_OCSP_INTERNAL_ERROR;
+    }
+#endif
+    intResponse = 0;
+    (*status) = static_cast<wrt_ocsp_widget_verification_status_t>(intResponse);
+    LogInfo("Widget verified with response " << intResponse);
+    return WRT_OCSP_OK;
+}